1.配置
import os
# 文件上传路径
UPLOAD_FOLDER = 'upload' # 最前面不能是/
# 系统绝对路径
basedir = os.path.abspath(os.path.dirname(__file__))
# 允许文件类型
ALLOWED_EXTENSIONS = set(['txt', 'png', 'jpg', 'xls', 'JPG', 'PNG', 'xlsx', 'gif', 'GIF'])
# 上传文件限制为最大 3 MB
MAX_CONTENT_LENGTH = 3 * 1024 * 1024
# 七牛云域名前缀
QINIU_DOMIN_PREFIX=''
2.七牛云配置
# -*- coding: utf-8 -*-
import logging
from qiniu import Auth,put_data
# 需要 Access Key 和 Secret Key
access_key = ''
secret_key = ''
# 要上传的空间
bucket_name = ''
def storage(data):
"""七牛云存储上传文件接口"""
if not data:
return None
try:
# 构建鉴权对象
q = Auth(access_key, secret_key)
# 生成上传 Token,可以指定过期时间等
token = q.upload_token(bucket_name)
# 上传文件
ret, info = put_data(token, None, data)
except Exception as e:
logging.error(e)
raise e
if info and info.status_code != 200:
raise Exception("上传文件到七牛失败")
# 返回七牛中保存的图片名,这个图片名也是访问七牛获取图片的路径
return ret["key"]
if __name__ == '__main__':
file_name = input("输入上传的文件")
with open(file_name, "rb") as f:
storage(f.read())
3.功能实现
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import request, send_from_directory
from api.user import user_url
from common import web_helper
from config import Config
import os
import time
from flask import current_app
from qiniu_storage import storage
# 判断文件后缀
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1] in Config.ALLOWED_EXTENSIONS
# 上传文件
def api_upload():
try:
file_dir = os.path.join(Config.basedir, Config.UPLOAD_FOLDER) # 拼接成合法文件夹地址
if not os.path.exists(file_dir):
os.makedirs(file_dir) # 文件夹不存在就创建
f=request.files['file'] # # 上传文件限制为最大 MB,超出直接返回None
if f and allowed_file(f.filename): # 判断是否是允许上传的文件类型
fname=f.filename
ext = fname.rsplit('.', 1)[1] # 获取文件后缀
unix_time = int(time.time())
new_filename = str(unix_time)+'.'+ext # 修改文件名
f.save(os.path.join(file_dir, new_filename)) #保存文件到upload目录
return web_helper.return_msg(1, '上传成功')
except Exception as e:
current_app.logger.error(e)
return web_helper.return_msg(-1, '服务器异常')
# 下载文件
@user_url.route('/download/<filename>', methods=['GET'])
def download(filename):
try:
file_dir=os.path.join('upload', filename)
if os.path.isfile(file_dir):
return send_from_directory('upload', filename, as_attachment=True)
except Exception as e:
current_app.logger.error(e)
return web_helper.return_msg(-1, '服务器异常')
# 七牛云上传文件
# @user_url.route('/qiniu', methods=['GET','POST'])
def qiniu_upload():
try:
file_dir = os.path.join(Config.basedir, Config.UPLOAD_FOLDER) # 拼接成合法文件夹地址
if not os.path.exists(file_dir):
os.makedirs(file_dir) # 文件夹不存在就创建
f=request.files['file'] # # 上传文件限制为最大 2 MB,超出直接返回None
if f and allowed_file(f.filename): # 判断是否是允许上传的文件类型
# 上传到七牛云,返回的url
url = storage(request.files['file'].read())
return Config.QINIU_DOMIN_PREFIX+url
return None
except Exception as e:
current_app.logger.error(e)
return web_helper.return_msg(-1, '服务器异常')