Django上传图片到七牛云

#先安装七牛云的包
pip install qiniu

views.py

from upload import upload

class UpPic(generics.CreateAPIView):
    def post(self, request, *args, **kwargs):
        img = request.FILES['img']
        url = upload(img)#upload方法在下面写
        return_dict = {"url": url}
        return Response(return_dict)

upload.py

from qiniu import Auth, put_file, etag, urlsafe_base64_encode, put_data
import uuid
from PIL import Image  #pip install pillow
import io


def upload(img):
    _img = img.read()
    size = len(_img) / (1024 * 1024)#上传图片的大小 M单位
    print(size)
    image = Image.open(io.BytesIO(_img))
    key = str(uuid.uuid1()).replace('-', '') + '.' + image.format
    access_key = '你的七牛云access_key'
    secret_key = '你的七牛云secert_key'
    q = Auth(access_key, secret_key)
    bucket_name = '你的bucket_name'
    token = q.upload_token(bucket_name, key, 3600, )
    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 倍
        print('压缩')
    else:
        print('不压缩')
        im = image
    # im = image
    im.save('./media/' + name) #在根目录有个media文件
    path = './media/' + name
    # up = im.read()
    ret, info = put_file(token, key, path)
    url = 'http://oq0zkmcec.bkt.clouddn.com/{}'.format(key)
    return url

猜你喜欢

转载自blog.csdn.net/qq_33042187/article/details/78738470