[英]Send Blob file via Axios
我有這樣的對象:
{
"name": "filename",
"size": 3523507,
"type": "image/png",
"extension": "png",
"url": "blob:http://localhost:8081/082e9c22-9869-4289-a9c8-e36b0640e61c"
}
我需要將其上傳到后端。 我試試看:
const session = axios.create({
baseURL: debug ? 'http://localhost:8000': '',
xsrfCookieName: CSRF_COOKIE_NAME,
xsrfHeaderName: CSRF_HEADER_NAME,
});
let formData = new FormData();
formData.append('file', file, 'file.name');
return session.post(`/chats/files/`,{...formData},), {
headers: {
"Content-Type": `multipart/form-data`,
}
}
但是將Blob添加到formData不起作用
UPD 我以這種形式從 vue-advanced-chat 組件中的 send-message 方法獲取了一個包含文件的對象:
{
"name": "filename",
"size": 3523507,
"type": "image/png",
"extension": "png",
"localUrl": "blob:http://localhost:8081/aae047a9-5f9e-481f-b0cc-17febe954c31",
"blob": {}
}
然后我在上傳到服務器之前格式化它以顯示在界面中
UPD2
我將 blob 轉換為文件
send_file(roomId, messageId, blob_file, isAudio, duration) {
let formData = new FormData();
let file = new File([blob_file.blob], blob_file.name);
formData.append('file[]', file, blob_file.name);
return session.post(`/chats/files/`,
{'chat': roomId, 'message': messageId, ...formData},), {
headers: {
'Content-Type': `multipart/form-data; boundary=${formData._boundary}`,
},
timeout: 30000,
}
},
仍然得到: {"file":["No files were sent."]}
您沒有以正確的方式發送數據。 它應該是:
export const uploadFileRequest = ({ file }) => {
const data = new FormData();
data.append('file', file, file.name);
return session.post(`/chats/files/`, data, {
headers: {
'Content-Type': `multipart/form-data;boundary=${data._boundary}`,
},
timeout: 30000,
});
};
它應該可以工作,供參考https://medium.com/@fakiolinho/handle-blobs-requests-with-axios-the-right-way-bb905bdb1c04
經過幾天的搜索,調試和數十次嘗試,我設法找到了解決方案。
let file = new File([blob_file.blob], fileName);
let fileName = `${blob_file.name}.${blob_file.extension}`;
formData.append('file', file, fileName);
formData.append('chat', roomId);
formData.append('message', messageId);
multipart/form-data
,並且不要指定 _boundary - 因為在新版本的 formData 中它是自動確定的!headers: {
'Content-Type': `multipart/form-data`,
},
所以代碼的最終版本如下所示:
send_file(roomId, messageId, blob_file) {
let formData = new FormData();
let fileName = `${blob_file.name}.${blob_file.extension}`;
let file = new File([blob_file.blob], fileName);
formData.append('file', file, fileName);
formData.append('chat', roomId);
formData.append('message', messageId);
return session.post(`/chats/files/`,
formData, {
headers: {
'Content-Type': `multipart/form-data`,
},
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.