[英]Django rest framework: How do I send and download xlsx file?
我已经被困一段时间了,现在试图使用 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 模型字段模型轻松完成此操作。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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.