本文介绍如何用预签名 URL 安全地让客户端端具备高性能的大文件上传能力。
暴露客户端代码
被反编译
Content-Type
Content-Length
通过后端 API 生成用于上传的预签名链接:putObject-presigned-url
客户端对 putObject-presigned-url 发起 PUT 请求,并完成文件上传
import boto3 from flask import Flask from flask import render_template_string from flask import request app = Flask(__name__) @app.get('/s3_upload_url') def get_upload_url(): # Config s3endpoint = 'https://s3.bitiful.net' # 请填入控制台 “Bucket 设置” 页面底部的 “Endpoint” 标签中的信息 s3region = 'cn-east-1' s3accessKeyId = '<--子账户 accessKey-->' # 请到控制台创建子账户,并为子账户创建相应 accessKey s3SecretKeyId = '<--子账户 secretKey-->' # !!切记,创建子账户时,需要手动为其分配具体权限!! # 连接 S3 client = boto3.client( 's3', aws_access_key_id = s3accessKeyId, aws_secret_access_key = s3SecretKeyId, endpoint_url = s3endpoint, region_name = s3region ) url = client.generate_presigned_url( 'put_object', Params={ 'Bucket': '<--缤纷云存储桶名-->', 'Key': request.args.get('key'), }, ExpiresIn=3600 ) return {'url': url}
<!DOCTYPE html> <html> <head> <title>S3 File Upload</title> </head> <body> <div> <h1>S3 File Upload</h1> <input type="file" id="file"> <button onclick="handleClick()">Upload</button> </div> <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.3.6/axios.min.js"></script> <script> let file; let fileContent; const fileInput = document.getElementById('file'); const fileReader = new FileReader(); fileInput.addEventListener('change', function (event) { file = event.target.files[0]; console.log("file is: ", file); fileReader.readAsArrayBuffer(file); }); fileReader.onload = function (event) { fileContent = event.target.result; // console.log("fileContent is: ", fileContent); }; function handleClick() { console.log('click'); const url = `/s3_upload_url`; const params = {key: '1.jpg'}; axios.get(url, {params: params}) .then(function (res) { console.log(res); const url = res.data.url; const config = { headers: { 'Content-Type': null, }, }; axios.put(url, file, config) .then(function (res) { console.log("res is: ", res); }); }); } </script> </body> </html>