前端上传文件到后端
前端
<form action="../uploadFile" method="post" enctype="multipart/form-data" style=" display: block;width: 100%; height: 20%;"><input type="file" name="file" id="file" ><br><input type="submit" value="导入文件" class="btn btn-primary" style="display: block;height: 40%;"></form>
后端
@csrf_exemptdef uploadFile(request):if request.method == 'POST':file_obj = request.FILES.get('file', None)print(file_obj.name)print(file_obj.size)with open('/Users/user3/PycharmProjects/djangoProject2/djangoProject2/' + file_obj.name, 'wb') as f:for line in file_obj.chunks():f.write(line)f.close()
前端点击下载后端文件
@csrf_exemptdef file_down(request):"""下载压缩文件:param request::param id: 数据库id:return:"""file_name = "result.xlsx"base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 项目根目录file_path = os.path.join(base_dir, 'upload', file_name) # 下载文件的绝对路径if not os.path.isfile(file_path): # 判断下载文件是否存在return HttpResponse("Sorry but Not Found the File")def file_iterator(file_path, chunk_size=512):"""文件生成器,防止文件过大,导致内存溢出:param file_path: 文件绝对路径:param chunk_size: 块大小:return: 生成器"""with open(file_path, mode='rb') as f:while True:c = f.read(chunk_size)if c:yield celse:breaktry:# 设置响应头# StreamingHttpResponse将文件内容进行流式传输,数据量大可以用这个方法response = StreamingHttpResponse(file_iterator(file_path))# 以流的形式下载文件,这样可以实现任意格式的文件下载response['Content-Type'] = 'application/octet-stream'# Content-Disposition就是当用户想把请求所得的内容存为一个文件的时候提供一个默认的文件名response['Content-Disposition'] = 'attachment;filename="{}"'.format(file_name)except:return HttpResponse("Sorry but Not Found the File")return response
url
re_path('download', views.file_down, name="download")
ui
<a href="/download/">下载图片</a>
