form表單上傳文件


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文件中設定上傳文件的路徑,或者在打開文件句柄的時候進行路徑拼接來把上傳的文件保存在指定的目錄下


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM