Vue 和 HTML FormData配合axios或ajax上传文件,提交表单数据
    		       		warning:
    		            这篇文章距离上次修改已过450天,其中的内容可能已经有所变动。
    		        
        		                
                在Vue中,你可以使用axios库来上传文件和提交表单数据。以下是一个简单的例子:
- 安装axios(如果你还没有安装):
 
npm install axios- 在你的Vue组件中使用axios上传文件和表单数据:
 
<template>
  <div>
    <form @submit.prevent="submitForm">
      <input type="text" v-model="formData.name" placeholder="Name">
      <input type="file" @change="selectFile">
      <button type="submit">Submit</button>
    </form>
  </div>
</template>
 
<script>
import axios from 'axios';
 
export default {
  data() {
    return {
      formData: {
        name: '',
        file: null
      }
    };
  },
  methods: {
    selectFile(event) {
      this.formData.file = event.target.files[0];
    },
    submitForm() {
      const formData = new FormData();
      formData.append('name', this.formData.name);
      formData.append('file', this.formData.file);
 
      axios.post('/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      .then(response => {
        // Handle response
        console.log(response);
      })
      .catch(error => {
        // Handle error
        console.log(error);
      });
    }
  }
};
</script>在这个例子中,我们创建了一个简单的表单,包含一个文本输入和一个文件输入。我们使用FormData来存储表单数据,并在用户提交表单时调用submitForm方法。在submitForm方法中,我们将文件和表单数据通过axios发送到服务器的/upload路径。
请注意,你需要根据你的服务器端点和API要求调整URL和headers。
评论已关闭