Django框架文件上传与自定义图片上传路径、上传文件名操作分析

yipeiwu_com7年前Python基础

本文实例讲述了Django框架文件上传与自定义图片上传路径、上传文件名操作。分享给大家供大家参考,具体如下:

文件上传

1、创建上传文件夹

在static文件夹下创建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">

文件数据存储在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、手动存储文件

存储到关联用户的表字段中

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内置存储

  • ImageField
    • 要导入pillow模块
  • FileField
  • 从request.FILES将文件获取出来,直接赋值给字段
  • 存储的时候,数据库存储的是路径
  • 存储在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 的参数是可调用的,则直接调用来生成文件名(包括静态文件夹后的文件路径)。要自定义上传文件名就从这里着手。

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)

按照上面的方式,就可以按照自己的意愿随意的处理文件名了(函数的参数个数是固定的)。

希望本文所述对大家基于Django框架的Python程序设计有所帮助。

相关文章

九步学会Python装饰器

本文实例讲述了Python装饰器。分享给大家供大家参考。具体分析如下: 这是在Python学习小组上介绍的内容,现学现卖、多练习是好的学习方式。 第一步:最简单的函数,准备附加额外功能...

PyTorch实现更新部分网络,其他不更新

torch.Tensor.detach()的使用 detach()的官方说明如下: Returns a new Tensor, detached from the current gra...

python中requests模块的使用方法

本文实例讲述了python中requests模块的使用方法。分享给大家供大家参考。具体分析如下: 在HTTP相关处理中使用python是不必要的麻烦,这包括urllib2模块以巨大的复杂...

python和c语言的主要区别总结

python和c语言的主要区别总结

Python可以说是目前最火的语言之一了,人工智能的兴起让Python一夜之间变得家喻户晓,Python号称目前最最简单易学的语言,现在有不少高校开始将Python作为大一新生的入门语言...

python matplotlib画图库学习绘制常用的图

python matplotlib画图库学习绘制常用的图

本文实例为大家分享了python matplotlib绘制常用图的具体代码,供大家参考,具体内容如下 github地址 导入相关类 import numpy as np import...