一、概述
文件上传时,文件数据存储在request.FILES属性中
二、存储路径
在static目录下创建upfile目录用于存储接收上传的文件
三、配置setting.py文件
加入:
MEDIA_ROOT=os.path.join(BASE_DIR,r'static\upfile')
四、注意
(1)from表单要上传文件需要加enctype="multipart/form-data"
(2)上传文件不能是GET,必须是POST
五、实例
首先制作模板文件upfile.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>上传文件</title> </head> <body> <form method="post" action="/savefile/" enctype="multipart/form-data"> <!--上传文件必须要加的--> <input type="file" name="file"/> <input type="submit" value="上传"/> </form> </body> </html>
再者配置url
url(r'^upfile/$',views.upfile), #upfile用来上传文件 url(r'^savefile/$',views.savefile), #savefile函数用来存储文件
写views.py
import os from django.conf import settings def upfile(request): return render(request,'myApp/upfile.html') def savefile(request): if request.method == "POST": #文件一定是要POST方法 f = request.FILES['file'] #在FILES中接收文件 #文件在服务器端的路径 filepath = os.path.join(settings.MEDIA_ROOT,f.name) with open(filepath,'wb') as fp: for info in f.chunks(): fp.write(info) #chunks是以文件流的方式来接受文件,分段写入 return HttpResponse('上传成功') else: return HttpResponse('上传失败!')