Django-上传图片(利用时间模块生成不重复的图片文件名)

1、配置文件:

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

2、创建表:

class Pic(models.Model):
	"""图片表"""
	image=models.CharField(max_length=255)

3、视图函数:

from django.shortcuts import render
from django.views import View
from datetime import datetime
from my_image import settings
from image_app import models
import os

class PicView(View):
	"""上传图片"""
	def get(self, request):
		"""显示表单页面"""
		images = models.Pic.objects.all()
		return render(request,'index.html',{'images':images})
	
	def  post(self, request):
		"""处理表单提交动作"""
		# 1、从页面请求获取图片文件
		picture = request.FILES.get('picture')    # 从表单获取图片文件
		if not picture:
			return render(request,'index.html',{'error':'请选择图片'})
	
		# 2、生成不重复的图片名
		#【注意:picture.name——这里的name是图片文件的名字,表的字段中没有name也可以获取到】
		pic_name = datetime.now().strftime('%Y%m%d%H%M%S%f')+'1' + picture.name
		
		# 3、拼接图片存储的完整路径
		#【注意:配置文件中路径形式定义为列表时,获取路径时要取索引为0】
		pic_path = os.path.join(settings.STATICFILES_DIRS[0], pic_name)    #将配置文件中的路径与图片名拼接
		
		# 4、将图片保存到服务器
		#【注意:打开的是图片存储的完整路径,并以二进制的方式写入;循环写入的是图片文件的块元素】
		with open(pic_path,'wb') as f:    # 打开图片路径
			for i in picture.chunks():    # 将图片文件拆分为块进行存储(默认:2.5M一块)【注意:是将图片拆分】
				f.write(i)
		
		# 5、将图片的相对路径上传到图片表的image字段中
		pic = models.Pic()
		pic.image='/static/' + pic_name    # 'static/'不加前面的斜杠也可以显示效果
		pic.save()
		
		return render(request,'index.html',{'error':'上传成功!'})

4、模板 index.html :




	
	上传图片


	
{% csrf_token %}
{{ error }} {#展示图片列表#} {% for i in images %} 图片 {% endfor %}

你可能感兴趣的:(Django)