在html页面通过js上传文件,直接看代码
<!DOCTYPE html>
<html>
<head>
<title>AWS S3 File Upload</title>
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.235.1.min.js"></script> //引用js-sdk
</head>
<body>
<input id="file-chooser" type="file"/>
<button id="upload-button">Upload</button>
<p id="results"><p></p>
<script type="text/javascript">
/// <reference types="aws-sdk" />
var credentials = {
accessKeyId: 'xxxxxxxx',
secretAccessKey: 'xxxxxxxxxxxxxx'
}; //秘钥形式的登录上传
AWS.config.update(credentials);
AWS.config.region = 'us-east-1'; //设置区域
// create bucket instance
var bucket = new AWS.S3({params: {Bucket: 'xxxxxxx'}}); //选择桶
var fileChooser = document.getElementById('file-chooser');
var button = document.getElementById('upload-button');
var results = document.getElementById('results');
button.addEventListener('click', function () {
var file = fileChooser.files[0];
if (file) {
results.innerHTML = '';
var params = {Key: file.name, ContentType: file.type, Body: file, 'Access-Control-Allow-Credentials': '*','ACL': 'public-read'}; //key可以设置为桶的相抵路径,Body为文件, ACL最好要设置
bucket.upload(params, function (err, data) {
console.log(err); //打印出错误
results.innerHTML = err ? 'ERROR!' : 'UPLOADED.';
});
} else {
results.innerHTML = 'Nothing to upload.';
}
}, false);
</script>
</body>
</html>
设置CORS
由于SDK通过Ajax提交数据,需要在S3桶策略中配置跨域提交的CORS. 示例中的*建议在生产环境中改成自己的域名.
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>PUT</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>DELETE</AllowedMethod>
<ExposeHeader>ETag</ExposeHeader> //一定要记得设置,否则分片上传的时候回报错
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
参考网址:https://amazonaws-china.com/cn/blogs/china/s3-multipul-upload-practice/