阿里云OSS-js分片上传

时间:2022-08-23 16:29:01

使用 aliyun-oss-sdk-4.4.4.min.js

方式一 客户端授权

https://help.aliyun.com/document_detail/32069.html

通过new OSS.Wapper()来创建client,OSS.Wrapper提供了异步的接口,类似于callback的方式,在.then()中处理返回的结果,在.catch()中处理错误。

注意这里暴露了accessKeySecret,实际应用中在客户端不可采用这种方式。

<body>
<script src="http://gosspublic.alicdn.com/aliyun-oss-sdk-4.4.4.min.js"></script>
  <input type="file" id="file" />
  <script type="text/javascript">
    var client = new OSS.Wrapper({
      region: '<oss region>',
      accessKeyId: '<Your accessKeyId>',
      accessKeySecret: '<Your accessKeySecret>',
      bucket: '<Your bucket name>'
    });
    document.getElementById('file').addEventListener('change', function (e) {
      var file = e.target.files[0];
      var storeAs = 'upload-file';
      console.log(file.name + ' => ' + storeAs);
      client.multipartUpload(storeAs, file).then(function (result) {
        console.log(result);
      }).catch(function (err) {
        console.log(err);
      });
    });
  </script>
</body>

 

方式二 采用服务端授权

https://github.com/rockuw/oss-in-browser

<script>
var
appServer = 'http://localhost:3000';//STS授权服务端 var bucket = 'js-sdk-bucket-sts'; var region = 'oss-cn-hangzhou'; var urllib = OSS.urllib; var OSS = OSS.Wrapper; var STS = OSS.STS; var applyTokenDo = function (func) { var url = appServer; return urllib.request(url, { method: 'GET' }).then(function (result) { var creds = JSON.parse(result.data); var client = new OSS({ region: region, accessKeyId: creds.AccessKeyId, accessKeySecret: creds.AccessKeySecret, stsToken: creds.SecurityToken, bucket: bucket }); return func(client); }); }; var progress = function (p) { return function (done) { var bar = document.getElementById('progress-bar'); bar.style.width = Math.floor(p * 100) + '%'; bar.innerHTML = Math.floor(p * 100) + '%'; done(); } }; var uploadFile = function (client) { var file = document.getElementById('file').files[0]; var key = document.getElementById('object-key-file').value.trim() || 'object'; console.log(file.name + ' => ' + key); return client.multipartUpload(key, file, { progress: progress }).then(function (res) { console.log('upload success: %j', res); return listFiles(client); }); }; window.onload = function () { document.getElementById('file-button').onclick = function () { applyTokenDo(uploadFile); } };
</script>

 NodeJS搭建的STS授权服务器

https://github.com/rockuw/node-sts-app-server