index.html文件 form表單中要加上 enctype="multipart/form-data"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h4>{{ error_message }}</h4>
<form action="/index/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p><input type="file" name="up_file"></p>
<input type="submit">
</form>
</body>
</html>
def index(request):
if request.method=="POST":
file_obj=request.FILES.get("up_file") #上傳的文件從request.FILES中取
f1=open(file_obj.name,"wb")
for i in file_obj.chunks():
# file.chunks() 將文件按塊寫入
f1.write(i)
f1.close()
return render(request,"index.html",locals())
選擇文件上傳,提交后,就可以在服務端后台看到所上傳的文件
可以在settings.py文件中設定上傳文件的路徑,或者在打開文件句柄的時候進行路徑拼接來把上傳的文件保存在指定的目錄下