javascript - Django rest 框架:如何发送和下载 xlsx 文件?
问题描述
我一直在尝试使用 django-rest-framework 将文件发送到客户端。我可以将其作为字节发送,但我不知道如何在客户端管理它以将其下载为 xlsx 文件。我尝试的一切都以损坏的文件结束。
这是我到目前为止所拥有的:
# views.py
from django.http import HttpResponse
from openpyxl import load_workbook
from openpyxl.writer.excel import save_virtual_workbook
class DownloadApiView(APIView):
authentication_classes = [BasicAuthentication, SessionAuthentication]
permission_classes = (IsAuthenticated,)
def post(self, request):
try:
file_path = './temp.xlsx'
pk = request.data['xml_id']
report = Report.objects.get(pk=pk)
wbrd = load_workbook(filename=file_path)
bytes = save_virtual_workbook(wb)
response = HttpResponse(bytes, content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
response['Content-Disposition'] = "attachment; filename=temp.xlsx"
return response
except Exception as error_msg:
logger.error(error_msg)
return Response({'error': 'Failed to retrieve file.'}, status=HTTP_400_BAD_REQUEST)
# client js called onclick()
function downloadFile(xmlID, type) {
let url = '/api/download_report/';
let $submit = $.ajax({
type: 'POST',
url: url,
data: JSON.stringify(inputData),
contentType: 'application/json',
headers: {"X-CSRFToken": getCookie("csrftoken")},
});
$submit.done(function (data) {
console.log(data);
let a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob(data, {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}));
a.download = 'temp.xlsx';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
});
}
解决方案
您可以使用 django 模型字段 models.FileField 轻松完成此操作,您可以按照本教程进行非常简短且易于理解的分步指南
https://blog.vivekshukla.xyz/uploading-file-using-api-django-rest-framework/
file = models.FileField(blank=False, null=False)
#you can edit this to
file = models.FileField(upload_to='/the path where you want to download files',blank=False, null=False)
推荐阅读
- node.js - 每个端口的 Windows EADDRINUSE (node.js)
- java - 我可以使用另一个注解作为 Spring @Qualifier 的值吗?
- python - 使用 not in 运算符打破 python 循环
- java - 我是 android studio 的新手,遇到了这个我不知道如何解决的错误
- javascript - Selenium:通过 AJAX 动态加载内容时刷新整个页面
- swift - 就像 App Store Connect 一样,在 UINavigationBar 的第二行添加一个段控件
- javascript - 如何在 JavaScript 中捕获无效的用户输入?
- python - Tkinter 事件的小部件属性不是小部件
- data-structures - 哨兵节点是否完全是虚拟节点?
- excel - 在 VBA excel 中为类变量赋值时,未设置该值。如何设置类声明变量?