阿里云 oss 前端上传组件封装

基本用法

  • 在首页引入SDK
  • 基本语法
const client = new OSS({
  region: 'oss-cn-hangzhou',
  accessKeyId: '',
  accessKeySecret: '',
  bucket: ''
});

client.list().then((result) => {
  console.log('objects: %j', result.objects);
  return client.put('my-obj', new OSS.Buffer('hello world'));
}).then((result) => {
  console.log('put result: %j', result);
  return client.get('my-obj');
}).then((result) => {
  console.log('get result: %j', result.content.toString());
});

基于OSS封装通用组件

假设我们基于Fusion来封装OSS,自定义request请求https://fusion.design/component/basic/upload

const processUpload = async (bucket, option) => {
  const { onSuccess, onError, file } = option;
  const store = await getStore(bucket); // 获取OSS存储对象
  option.onCancel = store.cancel.bind(store);

  try {
    await store.multipartUpload(file.name, file, {
      progress(p) {
        option.onProgress({ percent: p * 100 });
      },
    });
    const result = await store.list(); 
    onSuccess(_.extend({ name: file.name }, result));
  } catch (error) {
    onError(error);
  }
};

const customRequest = option => {
    processUpload(bucket, option);
    return {
      abort() {
        option.onCancel();
      },
    };
  };


        

参考

  • oss 上传 实例
    https://github.com/rockuw/oss-in-browser/blob/master/app.js
  • fusion upload 组件自定义实例
    https://github.com/alibaba-fusion/next/blob/master/src/upload/runtime/request.jsx

注意:

  • 分片上传出现错误
One or more of the specified parts could not be found or the specified entity tag might not have matched the part's entity tag

解决方案

暴露出的header加上etag。


阿里云 oss 前端上传组件封装_第1张图片
image.png
  • 前端跨域问题


    阿里云 oss 前端上传组件封装_第2张图片
    image.png

资料

OSS Browser
ali-oss github仓库

你可能感兴趣的:(阿里云 oss 前端上传组件封装)