【问题标题】:Post file with Axios and Vanilla JS使用 Axios 和 Vanilla JS 发布文件
【发布时间】:2019-01-14 11:15:15
【问题描述】:

我创建了一个可以接收文件的输入。单击提交按钮后,我设置了一个表单数据,尝试将文件附加到其中,然后向服务器发起 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/>

谢谢。

【问题讨论】:

  • 您的函数不包含e,这从您收到的错误消息中应该很明显。并且在.catch 之前缺少),以及各种开括号。
  • 首先,尝试将“e”作为参数添加到 onclick 函数中,这样您就可以在第 3 行的 append 函数中访问它。
  • 另外,e.dataTransfer 似乎只存在于 DragEvents,而不是 ClickEvents。您需要从输入中获取所选文件:document.querySelector('input').files[0](假设它是页面上唯一的&lt;input&gt;
  • @ChrisG 已更正。我在 SO 上快速而糟糕地复制了代码,我深表歉意。您的选择器有效。非常感谢!
  • @ArelSapir 很好发现 ;)!

标签: javascript input axios form-data


【解决方案1】:

尝试以这种方式附加 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);
            });

如果这没有帮助,那可能是服务器端的问题。

【讨论】:

    猜你喜欢
    • 2018-03-06
    • 2021-01-05
    • 2020-10-19
    • 1970-01-01
    • 2020-11-28
    • 1970-01-01
    • 2017-10-02
    • 1970-01-01
    • 2018-10-13
    相关资源
    最近更新 更多