Django 上传文件
setting.py:
MEDIA_ROOT = os.path.join(BASE_DIR,r'static\upfile')
urls.py:
url(r'^upfile/$',views.upfile), url(r'^savefile/$',views.savefile),
views.py:
def upfile(request): return render(request,'myApp/upfile.html') def savefile(request): if request.method == "POST": f = request.FILES['file'] filePath = os.path.join(settings.MEDIA_ROOT,f.name) with open(filePath,'wb') as fp: for info in f.chunks(): fp.write(info) return HttpResponse("上传成功") else: return HttpResponse("上传失败")
upfile.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>上传文件</title> </head> <body> <form action="/sunck/savefile/" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="file"> <input type="submit" value="上传"> </form> </body> </html>
1.在项目setting.py配置MEDIA_ROOT = os.path.join(BASE_DIR,r'static\upfile'),BASE_DIR代表项目目录,然后在项目目录下手动创建/static/upfile
2.url进入到/sunck/upfile,显示(上传文件的请求方式一定是post)
3.选择文件后点击上传,提交到/sunck/savefile,然后执行对应的视图函数,将文件保存到设置好的路径(filePath = os.path.join(settings.MEDIA_ROOT,f.name))
笔记:
1.f = request.FILE['file']里的file就是<input type="file" name="file">里的name属性值
2.f.chunks()是上传文件的内容
3.要以‘wb’(二进制写入)的方式打开,‘w’不行