django裡面檔案上傳處理處理

來源:互聯網
上載者:User

標籤:

最近,寫一個上次檔案的django。死活傳不過去。

在大神的協助下面,最終還是成。 不過也發現一個問題:

django 官網文檔:https://docs.djangoproject.com/en/1.8/topics/http/file-uploads/

表單定義

class UploadFileForm(forms.Form):    title = forms.CharField(max_length=50)    file = forms.FileField()

表單對象產生.

form = UploadFileForm(request.POST, request.FILES)

request.POST裡面是除了request.FILES外其他的參數,這裡比如title.


但是奇怪的是如果我UploadFileForm裡面只有一個tile。這裡寫成form = UploadFileForm( request.FILES),就是會報錯…………(悲催的我搞了好久沒明白,第一個參數)

發現這個第一個參數是被用來判斷布爾值的。難道是用來YY的?寫成UploadFileForm( {},request.FILES)就沒問題了。


順便貼下儲存方法:

def handle_upload_file(f):

    """save the file which is loaded """

    print(‘in handle‘)

    try:

        path = UPLOADED_FILE_DIRS + time.strftime(‘/%Y/%m/%d/%H/%M/%S/‘)

        print(path)

        if not int(os.path.exists(path)):

            os.makedirs(path)

            path_file_name = path+f.name

            print(path_file_name)

            destination = open(path_file_name, "wb+")

            for chuck in f.chunks():

                destination.write(chuck)

            destination.close()

    except Exception as e:

        print(e)

    return path_file_name



html中設定enctype="multipart/form-data"






django裡面檔案上傳處理處理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.