URL :
from django.conf.urls import url from app01 import views urlpatterns = [ url(r'^upload/', views.upload), ]
前端代码 :
<form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="file"> <input type="submit"> </form>
视图代码 :
import os from django.conf import settings def upload(request): if request.method == "POST": filename = request.FILES["file"].name #判断名字是否存在 if os.path.exists(os.path.join(settings.BASE_DIR, filename)): #假设文件后缀和文件名以"."区分 name, suffix = filename.split(".") #存在同名文件处理方法 name += "1" filename = name + "." +suffix with open(filename, "ab") as f: #chunks() 可以指定每次读取的具体大小 for chunk in request.FILES["file"].chunks(): f.write(chunk) return HttpResponse("OK") return render(request, "file.html")