后端代码
def download_material_res(request,name):
if name:
filepath = os.path.join(f"{xxx}/{name}")
if os.path.exists(filepath):
with open(filepath,"rb") as f:
os.unlink(filepath)
# 构造响应
response = HttpResponse(f.read(), content_type="application/octet-stream")
response['Content-Disposition'] = f'attachment; filename="newfile.xlsx"'
return response
else:
return HttpResponse(status=400)
使用httpresponse返回流
前端代码
function downloaderrorfile(newfile){
//下载后台生成的错误excel
const xhr = new XMLHttpRequest();
xhr.open('POST', "{url/"+newfile, true);
xhr.responseType = "blob";
xhr.onload = () => {
const blob = new Blob([xhr.response], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
const blobUrl = URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.download = "newfile.xlsx";
a.href = blobUrl;
a.target = '_blank';
a.click();
}
xhr.send(null)
}
要用XMLHttpRequest,ajax不可以...blob类型表可以看这个文章
Blob 下载文件时 type 类型 大全_blob type_派大星1的博客-CSDN博客
希望可以帮到你