Django上传图片到七牛云存储

七牛云可以帮助服务器转存图片等数据,类似于Dropbox等存储服务,专注文件存储的第三方服务商,服务较好。最近做到服务器存储图片的时候就想到用七牛来做,将图片或者文件存放在七牛,然后自己服务器只存放资源存放在七牛文件的url。

安装七牛云的包

pip install qiniu

Django项目配置

settings.py

QINIU_ACCESS_KEY = ‘你的七牛云access_key’
QINIU_SECRET_KEY = '你的七牛云secret_Key'
QINIU_BUCKET_NAME = '你的bucket_name'

uploadpic.pys上传

QINIU_ACCESS_KEY = '你的七牛云access_key'
QINIU_SECRET_KEY = '你的七牛云secert_key'
QINIU_BUCKET_NAME = '你的bucket_name'
uploadpic.py 上传方法
import io
import uuid

import qiniu
from PIL import Image
from django.conf import settings

q = qiniu.Auth(settings.QINIU_ACCESS_KEY, settings.QINIU_SECRET_KEY)

def upload(img):
    _img = img.read()
    size = len(_img) / (1024 * 1024)  # 上传图片的大小 M单位

    image = Image.open(io.BytesIO(_img))

    key = str(uuid.uuid1()).replace('-', '')

    name = 'upfile.{0}'.format(image.format)  # 获取图片后缀(图片格式)

    if size > 1:
        # 压缩
        x, y = image.size
        im = image.resize((int(x / 1.73), int(y / 1.73)), Image.ANTIALIAS) #等比例压缩 1.73 倍
    else:
        # 不压缩
        im = image

    im.save('./media/' + name)  # 在根目录有个media文件
    path = './media/' + name

    token = q.upload_token(settings.QINIU_BUCKET_NAME, key, 3600,)

    qiniu.put_file(token, key, path)
    url = 'http://7u2iif.com1.z0.glb.clouddn.com/{}'.format(key)
    return url
    

views.py

form web.uploadpic import upload

def uploadpic(request):
    image = request.FILES['file']
    url = upload(img)
    return HttpResponse(url)

引自这里

你可能感兴趣的:(Django上传图片到七牛云存储)