为什么我从 blob 生成的 javascript 中的 docx 充满了 [Object Object]?
Why my generated docx in javascript from a blob is filled with [Object Object]?
我通过 POST 请求将数据发送到我的 Django 后端,然后服务器使用该数据创建一个 docx 并将其发送回我尝试使用以下代码下载它的位置:
axios.post(route, data).then((res) => {
const filename = "report.docx"
var blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
var link = document.createElement('a');
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
link.href = downloadUrl;
link.style = "display: none";
link.download = filename;
document.body.appendChild(link)
link.click()
link.remove()
});
文件下载成功,但当我打开它时,它只包含 [Object Object],我做错了什么?我检查了后端并且文档已正确创建,因为当我在服务器中生成它时保存它时它具有正确的内容所以它要么是我发送它很糟糕,要么是在前端创建文件很糟糕。
这是我从后端发送它的方式:
#Generating the doc properly before this...
response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
report_filename = 'graph-report-'+now.strftime('%Y-%m-%d_%H-%M-%S')+'.docx'
response['Content-Disposition'] = 'attachment; filename=%s'%(report_filename)
document.save(response)
return response
谢谢你的帮助。
使用 Axios,axios.post(route, data).then((res) =>
中的 res
是一个响应对象。
返回的数据在res.data
.
中
- 执行
console.log(res.data)
以查看它确实是您期望的二进制数据。
- 执行
new Blob([res.data], ...
以使用该数据获取 blob。 (如果它已经是 Axios 提供的 blob,则您不必费心。)
(顺便说一句,你根本不需要为此使用 fetch()
和 createObjectURL
,因为你正在形成类似下载的二进制响应;这就足够了只需让浏览器 POST 您想要的数据,例如作为端点的表单;它会以相同的方式下载响应。)
我通过 POST 请求将数据发送到我的 Django 后端,然后服务器使用该数据创建一个 docx 并将其发送回我尝试使用以下代码下载它的位置:
axios.post(route, data).then((res) => {
const filename = "report.docx"
var blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
var link = document.createElement('a');
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
link.href = downloadUrl;
link.style = "display: none";
link.download = filename;
document.body.appendChild(link)
link.click()
link.remove()
});
文件下载成功,但当我打开它时,它只包含 [Object Object],我做错了什么?我检查了后端并且文档已正确创建,因为当我在服务器中生成它时保存它时它具有正确的内容所以它要么是我发送它很糟糕,要么是在前端创建文件很糟糕。
这是我从后端发送它的方式:
#Generating the doc properly before this...
response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
report_filename = 'graph-report-'+now.strftime('%Y-%m-%d_%H-%M-%S')+'.docx'
response['Content-Disposition'] = 'attachment; filename=%s'%(report_filename)
document.save(response)
return response
谢谢你的帮助。
使用 Axios,axios.post(route, data).then((res) =>
中的 res
是一个响应对象。
返回的数据在res.data
.
- 执行
console.log(res.data)
以查看它确实是您期望的二进制数据。 - 执行
new Blob([res.data], ...
以使用该数据获取 blob。 (如果它已经是 Axios 提供的 blob,则您不必费心。)
(顺便说一句,你根本不需要为此使用 fetch()
和 createObjectURL
,因为你正在形成类似下载的二进制响应;这就足够了只需让浏览器 POST 您想要的数据,例如作为端点的表单;它会以相同的方式下载响应。)