1. 程式人生 > >django檔案上傳

django檔案上傳

首先配置settings.py檔案,定義檔案上傳資料夾名稱和路徑

STATIC_URL = '/static/'
STATICFILES_DIRS=[
    os.path.join(BASE_DIR,"static")
]

MEDIA_ROOT=[
    os.path.join(BASE_DIR,"upload")
]
MEDIA_URL="/upload/"

前端HTML頁面

<form action="/fileUpload.html" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <p>username: <input type="text" name="username"></p>
    <p><input type="file" name="file"></p>
    <p><input type="submit" value="上傳"></p>
</form>

Views內容,這裡使用的Form元件驗證,但是沒寫內容,注意檔案上傳路徑及檔名稱,可以自行更改

from django.shortcuts import render,HttpResponse
from django import forms

#增加圖片上傳Form驗證
class fileForm(forms.Form):
    username = forms.CharField(
        min_length=2,
        error_messages={"min_lenth":"名字長度不夠"}
    )
    file = forms.FileField(
    )

# Create your views here.
def fileUpload(request):
    if request.method=="GET":
        return render(request,"fileupload.html")
    elif request.method=="POST":
        obj = fileForm(request.POST,request.FILES)
        if obj.is_valid():
            username=obj.cleaned_data["username"]
            file = obj.cleaned_data["file"]
            newfile = open("upload/"+file.name,"wb")
            for item in file.chunks():
                newfile.write(item)
            newfile.close()
            print(file.name,file.size,"ok")
            return HttpResponse("OK1111")
        else:
            print("NG")
            return HttpResponse("NG1111")
    else:
        print("hahaha")