-
压缩图片
// 上传图片通过 lrz 压缩
lrz(this.files[k], {
width: w
}) .then(function (rst) {
//压缩完成,提交至OSS
return uploadByOss(rst.file) ;// rst.file为上传文件的Blob 二进制格式
}).then(function(res){
//上传完成,开始下一步处理
console.log(res)
});
-
通过服务器获取上传OSS需要的policy,拼接后通过 new FormData() 直传oss
formData.append('file', file) // 必须放最后拼接,不然OSS会报 The bucket POST must contain the specified 'key'. If it is specified, please check the order of the fields
function uploadByOss (file) {
return new Promise(function(resolve , reject){ // Promise 一定要在函数的最外层才有效
$.ajax({
type: "get",
url: '/index.php?m=home&c=oss&a=index',
async: false,
cache: false
}).then(function (data) {
var re = eval ("(" + data + ")");
osssignature = {
//'key' : re.dir+'.jpg',
'policy': re.policy,
'OSSAccessKeyId': re.accessid,
'success_action_status' : '200',
'signature': re.signature,
'callback':re.callback,
};
var formData = new FormData()
for( var k in osssignature ){
formData.append(k, osssignature[k])
}
suffix = get_suffix(file.type); // 获取文件扩展名
formData.append("key", re.dir+suffix);
formData.append('file', file) // 必须放最后
var xhr = new XMLHttpRequest()
xhr.upload.addEventListener('progress', uploadProgress, false)
xhr.open('POST', re.host, true)
xhr.send(formData)
xhr.onload = () => {
if (xhr.status === 200 || xhr.status === 304) {
resolve(JSON.parse(xhr.response))
} else {
console.log(`error:error code ${xhr.status}`)
}
}
})
})
}