简体   繁体   English

使用 Axios 和 Vanilla JS 发布文件

[英]Post file with Axios and Vanilla JS

I have created an input that can receive a file.我创建了一个可以接收文件的输入。 Once the submit button is clicked, I set up a form Data, try to append the file to it, and then launch an axios post request to a server.单击提交按钮后,我设置了一个表单数据,尝试将文件附加到其中,然后向服务器发起 axios 发布请求。

Sadly, I don't know how to pass the file to formData:可悲的是,我不知道如何将文件传递给 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")
   })
}

What is the correction to add to e.dataTransfer.getData("files")?添加到 e.dataTransfer.getData("files") 的更正是什么? The input file can be an image, a pdf, etc. The input looks like that:输入文件可以是图像、pdf 等。输入如下所示:

<input type="file" multiple/>

Thanks.谢谢。

try to append the formData this way:尝试以这种方式附加 formData:

form.append('fieldName', 'fileBufferData', 'fileName');

Field name will be the name the server look up in the form.字段名称将是服务器在表单中查找的名称。 The buffer is the data/content of the file.缓冲区是文件的数据/内容。 And file name.. well.. it's the file name.和文件名......嗯......它是文件名。

Or it could be because you didn't set the header:或者可能是因为您没有设置标题:

            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);
            });

If this doesn't help it might be a problem on the server side.如果这没有帮助,则可能是服务器端的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM