images = models.ImageField('图片', upload_to='cicles/%Y/%m/%d', storage=ImageStorage(), null=True, blank=True)
from django.core.files.storage import FileSystemStorage
class ImageStorage(FileSystemStorage):
from django.conf import settings
def __init__(self, location=settings.MEDIA_ROOT, base_url=settings.MEDIA_URL):
super(ImageStorage, self).__init__(location, base_url)
def _save(self, name, content):
import os, time, random
ext = os.path.splitext(name)[1]
d = os.path.dirname(name)
fn = time.strftime('%Y%m%d%H%M%S')
fn = fn + '_%d' % random.randint(0, 100)
name = os.path.join(d, fn + ext)
return super(ImageStorage, self)._save(name, content)
接口请求接口
def save_userimg(request, img):
img_name = img.name
ext = os.path.splitext(img_name)[1]
print(img_name, ext)
fn = time.strftime('%Y%m%d%H%M%S')
fn = fn + '_%d' % random.randint(0, 100)
img_path = 'cicles'
times = datetime.datetime.now()
year = times.strftime('%Y')
month = times.strftime('%m')
day = times.strftime('%d')
img_path = os.path.join(img_path, year, month, day)
print("img_path:", img_path)
if not os.path.exists(os.path.join(settings.MEDIA_ROOT, img_path)):
os.makedirs(os.path.join(settings.MEDIA_ROOT, img_path))
print("新创建了文件夹")
filepath = os.path.join(settings.MEDIA_ROOT, img_path, fn + ext)
print("filepath:", filepath)
with open(filepath, 'wb') as fp:
for info in img.chunks():
fp.write(info)
img_url = "http://" + request.get_host() + "/media/" + img_path +fn + ext
return img_path + fn + ext