七牛云可以幫助服務(wù)器轉(zhuǎn)存圖片等數(shù)據(jù),類似于Dropbox等存儲(chǔ)服務(wù),專注文件存儲(chǔ)的第三方服務(wù)商钞诡,服務(wù)較好空郊。最近做到服務(wù)器存儲(chǔ)圖片的時(shí)候就想到用七牛來(lái)做攻冷,將圖片或者文件存放在七牛谦絮,然后自己服務(wù)器只存放資源存放在七牛文件的url题诵。
安裝七牛云的包
pip install qiniu
Django項(xiàng)目配置
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) # 在根目錄有個(gè)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)