Django-文件上传下载
Django中文件上传下载
上传
- form表单上传
- ajax上传
上传
上传可以分为form表单和ajax两种方式。
form表单上传
示例:
url.py配置
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^file_upload/', views.file_upload), ]
views.py
def file_upload(request): """ form表单上传文件 :param request: :return: """ if request.method == "POST": f1 = request.FILES.get("f1") with open(f1.name, "wb") as f: for i in f1.chunks(): # 一段一段去拿f1.chunks() f.write(i) return render(request, "form_upload.html")
form_upload.html
<div>
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="f1">
<input type="text" name="user">
<input type="submit" value="提交">
</form>
</div>
ajax上传文件
views.py
def file_upload(request): """ 文件上传 :param request: :return: """ if request.method == "POST": f1 = request.FILES.get("f1","") if f1: with open(f1.name,"wb") as f: for i in f1.chunks(): f.write(i) return JsonResponse({"status":True,"data":"上传成功"}) return JsonResponse({"status":False,"data":"上传文件不能为空"}) return render(request,"file_upload.html") file_upload.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>ajax上传文件</title> </head> <body> <input type="file" id="f1"> {% csrf_token %} <button id="b1">上传</button> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> $(function () { bindBtnClick(); }); function bindBtnClick(){ $("#b1").click(function () { var form_boj = new FormData(); # 实例化一个formdate对象 form_boj.append("f1",$("#f1")[0].files[0]); # jquery获取文件对象 form_boj.append("csrfmiddlewaretoken",$("[name='csrfmiddlewaretoken']").val()) # 处理csrftoken $.ajax({ url:{% url 'file_upload' %}, type:"post", data:form_boj, processData:false, # 不需要处理数据的编码格式 contentType:false, # 不需要处理contentType的请求头 success:function (res) { console.log(res.data); if (res){ alert(res.data) }else{ alert(res.data) } } }) }) } </script> </body> </html>
下载
view.py
from django.utils.encoding import escape_uri_path # 包含中文 from django.http import FileResponse def download_case_report(request, pk): """下载用例的执行报告,pk是用例的pk""" # 下载数据库中存放的html报告 api_obj = models.Api.objects.filter(pk=pk).first() # 下载 response = FileResponse(api_obj.api_report) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename="{0}.{1}"'.format(escape_uri_path(api_obj.api_name), "html") return response def download_local_file(request): """下载本地文件""" file = open("models.py", "rb") # 下载 response = FileResponse(file) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename="{0}.py"'.format(escape_uri_path("中文")) return response