123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- # coding=utf-8
- import os
- from PIL import Image
- from django.conf import settings
- from django.db import models
- from utils.file_operation import UploadFile, DeleteFile
- class UploadManager(models.Manager):
- def _addnew(self, file, path):
- width = None
- height = None
- path = UploadManager.calculatePath(path)
- filename = UploadFile(file, path)
- fullname = "%s%s" % (settings.MEDIA_ROOT, filename)
- size = os.path.getsize(fullname)
- try:
- img = Image.open(fullname)
- width, height = img.size
- #上传产品图片, 缩略图压缩宽或高最大200
- if width > 1440 and path == 'product_image/':
- img = img.resize((1440, int((height / width) * 1440)), Image.ANTIALIAS)
- img.save(fullname)
- width, height = img.size
- except:
- pass
- instance = self.model(
- picture="%s%s" % (settings.MEDIA_URL, filename),
- width=width,
- height=height,
- file_size="%.2f" % (float(size) / 1024),
- )
- instance.save()
- return instance
- def _update(self, file, path, upload):
- DeleteFile(upload.picture)
- width = None
- height = None
- path = UploadManager.calculatePath(path)
- filename = UploadFile(file, path)
- fullname = "%s%s" % (settings.MEDIA_ROOT, filename)
- size = os.path.getsize(fullname)
- try:
- img = Image.open(fullname)
- width, height = img.size
- # 缩略图压缩宽或高最大200
- # if width > 1440:
- # img = img.resize((1440, int((height / width) * 1440)), Image.ANTIALIAS)
- # img.save(fullname)
- # width, height = img.size
- except:
- pass
- Upload.objects.filter(id=upload.id).update(
- picture="%s%s" % (settings.MEDIA_URL, filename),
- width=width,
- height=height,
- file_size="%.2f" % (float(size) / 1024),
- )
- @staticmethod
- def calculatePath(path='user_image'):
- if path == 'commodity_image':
- return commodity_image
- elif path == 'user_image':
- return user_image
- commodity_image = "product_image/"
- user_image = "user_image/"
- class Upload(models.Model):
- picture = models.CharField(verbose_name=u'图片路径', max_length=250)
- width = models.IntegerField(verbose_name=u"图片宽度", blank=True, default=0)
- height = models.IntegerField(verbose_name=u"图片高度", blank=True, default=0)
- create_time = models.DateTimeField(verbose_name=u'上传时间', auto_now_add=True, editable=False)
- file_size = models.FloatField(verbose_name="文件大小", blank=True, default=0)
- objects = UploadManager()
- class Meta:
- db_table = 'system_upload'
- verbose_name = u'文件上传'
- ordering = ['-create_time']
- index_together = (
- 'create_time',
- )
- default_permissions = ()
- def del_images(self):
- picture = self.picture
- self.delete()
- DeleteFile(picture)
- def get_path(self):
- return '%s%s' % (settings.SERVER_DOMAIN, self.picture)
- def get_picture(self):
- return self.picture
|