Django框架文件上傳與自定義圖片上傳路徑、上傳文件名操作分析
本文實例講述了Django框架文件上傳與自定義圖片上傳路徑、上傳文件名操作。分享給大家供大家參考,具體如下:
文件上傳
1、創(chuàng)建上傳文件夾
在static文件夾下創(chuàng)建uploads用于存儲接收上傳的文件
在settings中配置,
MEDIA_ROOT=os.path.join(BASE_DIR,r'static/uploads')
2、定義上傳表單
<form action="{% url 'app:do_upload' %}" method="post" enctype="multipart/form-data">
文件數(shù)據(jù)存儲在request.FILES
屬性中
文件上傳必須使用POST請求方式
<form method='post' action='x' enctype='multipart/form-data'> {% csrf_token %} <input type='file' name='icon'> <input type='submit' value='上傳'> <form>
3、手動存儲文件
存儲到關(guān)聯(lián)用戶的表字段中
def savefIcon(request): if request.method == 'POST' f = request.FILES['icon'] filePath = os.path.join(settings.MEDIA_ROOT,f.name) with open(filePath,'wb') as fp: for part in f.chunks(): fp.write(part)
4、django內(nèi)置存儲
- ImageField
- 要導(dǎo)入pillow模塊
- FileField
- 從request.FILES將文件獲取出來,直接賦值給字段
- 存儲的時候,數(shù)據(jù)庫存儲的是路徑
- 存儲在MEDIA_ROOT
自定義圖片上傳路徑和上傳文件名
圖片上傳中,如果不對上傳的文件名做處理,很容易引起文件名重復(fù),這會覆蓋之前上傳的圖片,django提供了自定義上傳文件名的方法。
def generate_filename(self, instance, filename): """ Apply (if callable) or prepend (if a string) upload_to to the filename, then delegate further processing of the name to the storage backend. Until the storage layer, all file paths are expected to be Unix style (with forward slashes). """ if callable(self.upload_to): filename = self.upload_to(instance, filename) else: dirname = datetime.datetime.now().strftime(self.upload_to) filename = posixpath.join(dirname, filename) return self.storage.generate_filename(filename)
上面的代碼是django中對ImageField上傳時,生成文件名的處理方式。如果 upload_to 的參數(shù)是可調(diào)用的,則直接調(diào)用來生成文件名(包括靜態(tài)文件夾后的文件路徑)。要自定義上傳文件名就從這里著手。
import uuid from django.db import models def image_upload_to(instance, filename): return 'original_image/{uuid}/{filename}'.format(uuid=uuid.uuid4().hex, filename=filename) class TestImageUpload(models.Model): image = models.ImageField(upload_to=image_upload_to)
按照上面的方式,就可以按照自己的意愿隨意的處理文件名了(函數(shù)的參數(shù)個數(shù)是固定的)。
希望本文所述對大家基于Django框架的Python程序設(shè)計有所幫助。
相關(guān)文章
Python中文分詞工具之結(jié)巴分詞用法實例總結(jié)【經(jīng)典案例】
這篇文章主要介紹了Python中文分詞工具之結(jié)巴分詞用法,結(jié)合實例形式總結(jié)分析了Python針對中文文件的讀取與分詞操作過程中遇到的問題與解決方法,需要的朋友可以參考下2017-04-04詳解pyqt中解決國際化tr()函數(shù)不起作用的問題
本文主要介紹了pyqt中解決國際化tr()函數(shù)不起作用的問題,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02在tensorflow中實現(xiàn)屏蔽輸出的log信息
今天小編就為大家分享一篇在tensorflow中實現(xiàn)屏蔽輸出的log信息,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02SublimeText 2編譯python出錯的解決方法(The system cannot find the file
這篇文章主要介紹了SublimeText 2編譯python報The system cannot find the file specified錯誤的解決方法,大家參考使用吧2013-11-11