[英]Ajax file upload Vue.js
I am trying to upload a file via Ajax using Vue.js - however, the server keeps responding saying that the file needs to be an image (It works when it isn't using ajax). 我正在尝试使用Vue.js通过Ajax上传文件 - 但是,服务器一直在回复说该文件需要是一个图像(它在不使用ajax时有效)。 The setup I have is as follows:
我的设置如下:
<input type="file" name="avatar" v-model="profileFormData.avatar">
And my data is: 我的数据是:
profileFormData: {
"name": '',
"email": '',
"avatar": '',
},
Is there something specific I need to do for file uploads? 我是否需要为文件上传做些具体的事情?
I seem to have found the fix for this. 我似乎找到了解决这个问题的方法。 Firstly I had to remove the v-model from the form element (and every element within that form).
首先,我必须从表单元素(以及该表单中的每个元素)中删除v模型。 Then rather than posting v-model, get the data to send using
FormData
. 然后,不是发布v-model,而是使用
FormData
获取要发送的数据。
Here is an example: 这是一个例子:
//Pass the form into a new FormData object
var formData = new FormData(this.el);
//Pass through the object instead of data passed via a v-model
this.vm
.$http[this.getRequestType()](this.el.action, formData)
.then(this.onComplete.bind(this))
.catch(this.onError.bind(this));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.