需求:公司有项目需要将原先服务器上的图片转移到AWS的S3 储存桶中 ,前端的上传图片也需要重新编写,
1.先引入
npm install aws-sdk --save
2.直接看代码
import { MEDIASOURCE } from '@/api'; //自己代码中获取接口
const AWS = require('aws-sdk');
// 秘钥信息,以及桶信息 由后端提供
var albumBucketName = "xxxxxxxx"; //桶名字
// 实例化aws对象
var s3 = new AWS.S3({
accessKeyId: "xxxxxxxx",
secretAccessKey: "xxxxxxxx",
region: "xxxxxxxx",
});
//UUID生成唯一key值
function generateUUID() {
var d = new Date().getTime();
var uuid = 'xxxxxxxxxxxx4xxxyxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c == 'x' ? r : (r & 0x3) | 0x8).toString(16);
});
return uuid;
}
// aws上传文件获取aws签名
export async function upLoadCosFile(file) {
return new Promise(async (resolve, reject) => {
var photoKey ='image/'
+ generateUUID(file.name.split('.')[0])
+'.' +file.name.split('.')[1];
s3.upload({
Bucket: albumBucketName,
Key: randomFileName,
Body: file,
}, async (err)=>{
if (err) {
console.log("Error", err)
reject(err);
return
}
//保存上传资源属性接口的参数
let obj = {
awsKey: randomFileName,
fileName: file.name,
mediaLength: file.size,
};
// 资源数据传送到后端
const media_resource = await MEDIASOURCE.save_media_resource(obj); //保存上传资源属性的接口
resolve(media_resource);
})
});
}
踩坑:
Error: No access to ETag property on response.
Check CORS configuration to expose ETag header.
(在浏览器中使用AWS的SDK直接上传文件到S3时,需要在S3 Bucket上配置CORS才能成功上传,否则ajax请求会被浏览器拦截)
注:跨域官方文档 (https://docs.aws.amazon.com/zh_cn/AmazonS3/latest/userguide/cors-troubleshooting.html)
参考:
(https://www.cnblogs.com/duhuo/p/14828021.html)
跨域 — 后端配置。
注:官方文档
https://docs.aws.amazon.com/zh_cn/sdk-for-javascript/v2/developer-guide/s3-example-photo-album.html