1.configuración: consulte la ruta de guardado del archivo de carga de configuración, y el archivo se cargará correctamente y se guardará en esta carpeta:
MEDIA_ROOT = os.path.join (BASE_DIR, "estático")
2. Recepción y guardado de archivos en views.py:
de django.conf importar la configuración de django.http importar HttpResponse, HttpResponseRedirect # 上传 文 见 def uploadfile (request): return render (request, 'mian / upfile.html') # 文件 保存 def savefile (request): print (request. método) if request.method == 'POST': f = request.FILES ['myfile'] filepath = os.path.join (settings.MEDIA_ROOT, f.name) with open (filepath, 'wb') as fp: para obtener información en f.chunks (): fp.write (info) fp.close () return HttpResponse ('上传 成功') else: return HttpResponse ('上传 失败')
3. Cargar página (al cargar archivos en forma de formulario, debe escribirse como: enctype = "multipart / form-data", el tipo de entrada debe ser archivo):
<! DOCTYPE html> <html lang = "en"> <head> <meta charset = "UTF-8"> <title> Título </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 =" subir "/> </form> </body> </html>