js 封装阿里云OSS文件上传

197 阅读1分钟
import OSS from 'ali-oss';

class OssService {
  constructor(region, accessKeyId, accessKeySecret, bucket) {
    this.client = new OSS({
      region,
      accessKeyId,
      accessKeySecret,
      bucket,
    });
  }

  async uploadImage(file) {
    try {
      const fileName = Date.now() + '.' + file.name.split('.').pop().toLowerCase();
      const result = await this.client.put(fileName, file);
      return result.url;
    } catch (err) {
      console.error(err);
      return null;
    }
  }

  async deleteImage(url) {
    try {
      const fileName = url.split('/').pop();
      await this.client.delete(fileName);
    } catch (err) {
      console.error(err);
    }
  }

  async updateImage(url, newFile) {
    try {
      await this.deleteImage(url);
      const newUrl = await this.uploadImage(newFile);
      return newUrl;
    } catch (err) {
      console.error(err);
      return null;
    }
  }

  async getImage(url) {
    try {
      const fileName = url.split('/').pop();
      const result = await this.client.get(fileName);
      return result.content;
    } catch (err) {
      console.error(err);
      return null;
    }
  }
}

export default OssService;

使用方法示例:

import OssService from './oss-service';

// 创建 OssService 实例
const ossService = new OssService('your-region', 'your-accessKeyId', 'your-accessKeySecret', 'your-bucket');

// 调用方法
const file = new File(['hello world'], 'hello.txt');
const url = await ossService.uploadImage(file);
console.log(url);

await ossService.deleteImage(url);

const newFile = new File(['new content'], 'new.txt');
const newUrl = await ossService.updateImage(url, newFile);
console.log(newUrl);

const content = await ossService.getImage(newUrl);
console.log(content);

在使用时,只需要创建一个 OssService 实例,然后调用相应的方法即可。该示例代码中的 your-regionyour-accessKeyIdyour-accessKeySecretyour-bucket 都需要替换为你自己的阿里云 OSS 的信息。`