1.settings: See the save path for the configuration upload file, and the file will be uploaded successfully and saved to this folder:
MEDIA_ROOT=os.path.join(BASE_DIR,"static")
2. File receiving and saving in 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. Upload page (when uploading files in form form, it must be written as: enctype="multipart/form-data", input type must be 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>