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、手動存儲文件
存儲到關聯(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
- 要導入pillow模塊
- FileField
- 從request.FILES將文件獲取出來,直接賦值給字段
- 存儲的時候,數(shù)據(jù)庫存儲的是路徑
- 存儲在MEDIA_ROOT
自定義圖片上傳路徑和上傳文件名
圖片上傳中,如果不對上傳的文件名做處理,很容易引起文件名重復,這會覆蓋之前上傳的圖片,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程序設計有所幫助。
相關文章
Python技法之簡單遞歸下降Parser的實現(xiàn)方法
遞歸下降解析器可以用來實現(xiàn)非常復雜的解析,下面這篇文章主要給大家介紹了關于Python技法之簡單遞歸下降Parser的實現(xiàn)方法,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考下2022-05-05
妙用itchat! python實現(xiàn)久坐提醒功能
python編寫的久坐提醒,給最愛的那個她,這篇文章主要為大家分享了python久坐提醒功能的實現(xiàn)代碼,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-11-11
PyTorch中torch.tensor與torch.Tensor的區(qū)別詳解
這篇文章主要介紹了PyTorch中torch.tensor與torch.Tensor的區(qū)別詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-05-05
Python 多模式字符串搜索 Aho-Corasick詳解
Aho-Corasick 算法是一種用于精確或近似多模式字符串搜索的高效算法,本文給大家介紹Python 多模式字符串搜索 Aho-Corasick的相關知識,感興趣的朋友跟隨小編一起看看吧2025-01-01

