因为我们出口的带宽限制,测试经常找我给他上传个包到阿里云的对象存储,虽然传起来也不是很费事,但是出于运维的职业素养,特意写了一个自动上传的接口,代码如下:
# -*- coding: UTF-8 -*-
from flask import Flask,request,jsonify
import oss2
app = Flask(__name__) #创建一个应用实例,__name__是Pyhon的一个内置变量
auth = oss2.Auth('<yourAccessKeyId>', '<yourAccessKeySecret>')
bucket = oss2.Bucket(auth,'<oss_endpoint>', '<yourBucketName>')
#处理跨域请求
@app.after_request #flask装饰器
def after_request(response):
response.header.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
return response
#上传文件接口
@app.route('/upload',methods=['POST'])
def upload_file():
if 'file' not in request.files:
return jsonify({'error': 'No file part'})
file = request.file['file']
if file.filename == '':
return jsonify({'error': 'please select file'})
if file:
filename = file.filename
# 指定上传到OSS的目录,这里根据自己事情情况写
oss_path = 'front/' + filename
# 获取文件大小
file_size = len(file.read())
file.seek(0)
#上传文件,并返回上传进度
def percentage(consumed_bytes,total_bytes):
if total_bytes:
percentage = int(100 * (consumed_bytes / total_bytes))
return jsonify({'progress': percentage})
bucket.put_object(oss_path,file,progress_callback=percentage)
#生成分享链接
share_link= bucket.sign_url('GET',oss_path,60*60) #有效期一小时,我本来想用的 但是后来发现生成的链接带了明文的key和KeySecret,所以我在前端做了一个拼接
return jsonify({'message': '上传成功',share_link: share_link,'filename': filename})
if __name__ == '__main__':
app.run(debug=True)
前端代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Upload to OSS</title>
</head>
<body>
<h1>Upload to OSS</h1>
<input type="file" id="fileInput">
<button onclick="uploadFile()">Upload</button>
<div id="progressText"></div>
<div id="result"></div>
<script>
function uploadFile() {
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
const formData = new FormData();
formData.append('file', file);
const progressText = document.getElementById('progressText');
const resultDiv = document.getElementById('result');
const xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', (event) => {
if (event.lengthComputable) {
const percentComplete = Math.round((event.loaded / event.total) * 100);
const displayPercent = Math.floor(percentComplete / 10) * 10;
progressText.innerHTML = `上传进度: ${displayPercent}%`;
}
});
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
resultDiv.innerHTML = `<p style="color: green;">上传成功!分享链接:
<a target="_blank">http://zenx-miniapp.oss-cn-beijing.aliyuncs.com/front/${response.filename}</a>
</p>`;
} else {
resultDiv.innerHTML = `<p style="color: red;">上传失败!</p>`;
}
}
};
xhr.open('POST', 'http://localhost:5000/upload');
xhr.send(formData);
}
</script>
</body>
</html>
nginx转发配置:
server{
listen 80;
server_name localhost;
location / {
root /data/uposs;
index index.html;
}
}
以上代码修改下AccessKeyId, AccessKeySecret,oss_endpoint,yourBucketName,然后注意一下bucket里面的目录和代码里同步下就可以直接用了。
做了十年运维了,以前能手动搞就麻烦下手动搞,可是现在时代不同了,能用脚本实现的不要再去浪费时间一下一下点了。