問題:
公司的需求是從mongodb中查找數據並下載回本地,但是在將文件從mongodb通過django服務端,然后從django服務端向瀏覽器下載文件。但是在下載的時候出了些問題。由於是用的ajax請求,異步的,所以在將文件返回到前端的時候,前端的script標簽中的success回調函數中有數據,且是string類型。
解決辦法:
在回調函數中設置重定向到文件所在的url
——代碼——
django下載文件到瀏覽器:
from django.http import FileResponse def filedownload(request,filepath): file = open(filepath, 'rb') response = FileResponse(file) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename="example.tar.gz"' return response
前端script標簽中的ajax請求:
<script> $(".sub").on("click", function () { $.ajax({ url: "/download", type: "post", data: { id1: $("#id1").val(), id2: $("#id2").val(), start_date: $("#start_date").val(), end_date: $("#end_date").val(), }, success: function (data) { var path = data.path; location.href = path # 重定向到文件所在的路徑 } }) }); </script>