我有这样的对象:
{
"name": "filename",
"size": 3523507,
"type": "image/png",
"extension": "png",
"url": "blob:http://localhost:8081/082e9c22-9869-4289-a9c8-e36b0640e61c"
}
Run Code Online (Sandbox Code Playgroud)
我需要将其上传到后端。我尝试一下:
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`,
}
}
Run Code Online (Sandbox Code Playgroud)
但是将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": {}
}
Run Code Online (Sandbox Code Playgroud)
然后我将其格式化为在上传到服务器之前显示在界面中
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,
}
},
Run Code Online (Sandbox Code Playgroud)
仍然得到:{“file”:[“没有发送文件。”]}
经过几天的搜索、调试和数十次尝试,我终于找到了解决方案。
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);
Run Code Online (Sandbox Code Playgroud)
multipart/form-data,并且不指定 _boundary - 因为在新版本的 formData 中它是自动确定的!headers: {
'Content-Type': `multipart/form-data`,
},
Run Code Online (Sandbox Code Playgroud)
所以代码的最终版本如下所示:
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`,
},
})
Run Code Online (Sandbox Code Playgroud)