1.settings:配置上传文见保存路径,文件上传成功会,保存到这个文件夹下:
MEDIA_ROOT=os.path.join(BASE_DIR,"static")
2.views.py 中实现文件接收和保存:
from django.conf import settings from django.http import HttpResponse, HttpResponseRedirect #上传文见 def uploadfile(request): return render(request, 'mian/upfile.html') # 文件保存 def savefile(request): print(request.method) if request.method == 'POST': f = request.FILES['myfile'] filepath = os.path.join(settings.MEDIA_ROOT, f.name) with open(filepath, 'wb') as fp: for info in f.chunks(): fp.write(info) fp.close() return HttpResponse('上传成功') else: return HttpResponse('上传失败')
3.上传页面(form 表单上传文件时,必须写成:enctype="multipart/form-data",input 类型必须是file):
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form enctype="multipart/form-data" action="/mian/savefile/" method="POST"> {% csrf_token %} <input type="file" name="myfile" /> <br/> <input type="submit" value="upload"/> </form> </body> </html>