首先要在python 中安装qiniu
使用 pycharm可以很方便的安装,打开project interpreter,然后搜索即可
coding: utf-8
from django.shortcuts import redirect, render, HttpResponse
import json
import os
import uuid
from blog import models
import qiniu
import logging
七牛云上传图片配置
access_key = 'xxxx'
secret_key = 'xxxx'
bucket_name = 'store1' #填你的bucket名
remote_url_prefix = 'xxxx' # 用于拼接img网址
def upload(reqeust):
'''
将文件进行上传
:param reqeust:
:return: 返回wang editor所要求的数据
'''
image = reqeust.FILES.get('image', None)
img_url = qiniu_upload(image)
print(img_url)
result = {"errno": 0, 'data': [img_url, ]} # 给wang editor返回的参数
return HttpResponse(json.dumps(result))
def qiniu_upload(file):
"""
使用七牛云
:param file:
:return:
"""
binary_file = file.read()
q = qiniu.Auth(access_key, secret_key)
token = q.upload_token(bucket=bucket_name, )
result, response_info = qiniu.put_data(token, None, binary_file)
image_remote_url = remote_url_prefix+'/'+result.get('hash') # 使用返回值拼接网址得到img网址
return image_remote_url
再附上普通的写法(通过IO写入本地文件):
def normal_upload(image):
"""
普通方式上传,写入本地文件
:param image: 从request获取的image
:return:
"""
cwd = os.getcwd()
myuuid = str(uuid.uuid1()).replace('-', '')
new_filename = myuuid + image.name
relative_path = os.path.join(r'blogupload', new_filename)
file_upload_url = os.path.join(cwd, relative_path)
logging.info(f'上传了图片,位置:{file_upload_url}')
# os.makedirs(file_upload_url)
with open(file_upload_url, mode="wb+") as f: # 将文件写入blog下的upload文件夹
for chunk in image.chunks():
f.write(chunk)
img_url = "http://localhost:8000/static/" + new_filename # upload配置了static,也需要用static访问