如何在vue.js中将文件和数据追加到FormData

ban*_*nky 2 vue.js

我正在尝试将上传的文件和数据值附加到vue.js中的FormData。在我的控制器中,只能评估文件请求。

    data() {
       return (
          file: '',
          categ: ''
        }
}
Run Code Online (Sandbox Code Playgroud)

在我的方法中:

Var form = new FormData();
var file = this.file;
var cat = this.categ;
form.append('pics', file, cat);

axios.post('/api', form,
{ headers: {'Content-Type': 'multipart/form-data'}
}).then (res =>{ console.log(res)});  
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

sam*_*ayo 5

问题是您可能如何从输入中获取文件。

如果您的输入如下所示:

 <input type="file"  @change="upload($event)" id="file-input">
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用$event获取file和将其用作:

methods: {
  upload(event){
    let data = new FormData();
    let file = event.target.files[0];

    data.append('name', 'my-file')
    data.append('file', file)

    let config = {
      header : {
       'Content-Type' : 'multipart/form-data'
     }
    }

    axios.post('/api', data, config).then(
      response => {

      }
    )
  }
}
Run Code Online (Sandbox Code Playgroud)