drf+vue实现文件下载
后端代码:
re_path(r'^package/download/(?P<file_path>.*)/$', views.PackageDownload.as_view({'post': 'file_download'}))
from django.http import Http404, FileResponse
class PackageDownload(viewsets.ModelViewSet): permission_classes = [IsAuthenticated] def file_download(self, request, file_path): ext = os.path.basename(file_path).split('.')[-1].lower() # cannot be used to download py, db and sqlite3 files. if ext not in ['py', 'db', 'sqlite3']: response_file = FileResponse(open(file_path, 'rb')) response_file['content_type'] = "application/octet-stream" response_file['Content-Disposition'] = 'attachment; filename=' + os.path.basename(file_path) return response_file else: raise restful.params_error("不允许的请求")
这里要判断一下文件类型,保证安全。
前端代码:
前端需要处理后端接口返回过里的二进制文件:



浙公网安备 33010602011771号