簡體   English   中英

使用 Axios 和 Vanilla JS 發布文件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM