[英]Post file with Axios and Vanilla JS
我创建了一个可以接收文件的输入。 单击提交按钮后,我设置了一个表单数据,尝试将文件附加到其中,然后向服务器发起 axios 发布请求。
可悲的是,我不知道如何将文件传递给 formData:
button.onclick = function(){
let formData = new FormData();
formData.append('myFile', e.dataTransfer.getData("files"));
axios.post("/api/upload", formData)
.then(response =>{
console.log(response.data)})
.catch(err=> {
console.log("error")
})
}
添加到 e.dataTransfer.getData("files") 的更正是什么? 输入文件可以是图像、pdf 等。输入如下所示:
<input type="file" multiple/>
谢谢。
尝试以这种方式附加 formData:
form.append('fieldName', 'fileBufferData', 'fileName');
字段名称将是服务器在表单中查找的名称。 缓冲区是文件的数据/内容。 和文件名......嗯......它是文件名。
或者可能是因为您没有设置标题:
let form = new FormData();
form.append('field', 'buffer', 'fileName');
axios.post('/api/upload', form, {
headers: {
'Content-Type': `multipart/form-data; boundary=${form._boundary}`
}
}).then((res) => {
console.log(res.data);
}).catch((err) => {
console.log(err);
});
如果这没有帮助,则可能是服务器端的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.