阿里云OSS STS 切片上传 示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>阿里云OSS STS 切片上传</title> <script src="http://cdn.bootcss.com/jquery/1.11.1/jquery.min.js"></script> <script type="text/javascript" src="//gosspublic.alicdn.com/aliyun-oss-sdk-6.16.0.min.js"></script> <script> //阿里云sts切片上传 window.client, window.sts; window.getStsToken = function () { return new Promise(function (resolve, reject) { $.ajax({ url: '/artivity_token?id=34', dataType: 'json', contentType: 'application/json', type: 'get', success: function (result) { window.sts = JSON.parse(result); client = new OSS({ region: "oss-cn-qingdao", accessKeyId: sts.AccessKeyId, accessKeySecret: sts.AccessKeySecret, stsToken: sts.SecurityToken, bucket: "gh-vote", }); resolve(1) }, error: function (error) { resolve(0) } }); }); } //AliOss STS 单文件切片上传 window.stsSignUpload = function (file) { return new Promise(function (resolve, reject) { getStsToken().then(function (res) { if (res == 1) { const options = { progress: (p, cpt, res) => { console.log(parseInt(p * 100) + '%'); //控制进度条 }, parallel: 4, partSize: 1024 * 1024, meta: { year: 2024, people: "gh" }, mime: "text/plain", }; var fileArr = file.name.split('.'); var extName = fileArr[fileArr.length - 1]; var saveDir = 'ghvoting/';//可以设置在阿里云OSS的保存目录,存根目录留空就可以了 var newFileName = saveDir + 'ghvoting_' + Date.now() + '.' + extName; // 分片上传 client.multipartUpload(newFileName, file, { ...options }).then(function (res) { if (res.res.status == 200) { let back = { code: 0, msg: '上传成功', data: res.res.requestUrls[0] }; resolve(back); } }); } else { let back = { code: 1, msg: '上传失败', data: '' }; resolve(back); } }); }); } //AliOss STS 多文件切片上传 window.stsMultipleUpload = async function (files) { let fileArr = []; for (let i = 0; files.length > i; i++) { // console.log('files->'+i, files[i]); let file = await stsSignUpload(files[i]); if (file.code == 0) { fileArr.push(file.data); } } let back = { code: 1, msg: '上传失败', data: '' }; if (fileArr.length > 0) { back.code = 0; back.msg = '上传成功'; back.data = fileArr; } return back; } </script> <style> .item {margin: 30px;} </style> </head> <body> <div class="sign item"> <input id="file" type="file" /> <button id="submit_sign">单文件上传</button> </div> <div class="multiple item"> <input id="files" type="file" multiple /> <button id="submit_multiple">多文件上传</button> </div> <div id="progress"> </div> <div id="resImg"> </div> <script type="text/javascript"> //单文件上传 $('#submit_sign').click(function(){ let file = document.getElementById('file').files[0]; stsSignUpload(file).then(function(res){ console.log('单文件上传->',res); }); }); //多文件上传 $('#submit_multiple').click(function () { let files = document.getElementById('files').files; stsMultipleUpload(files).then(function (res) { console.log('多文件上传->', res); }); }); </script> </body> </html>