前端直传华为云对象存储obs

1,444 阅读1分钟

项目中经常会做文件上传的需求,一般都是直接上传文件给后端,还有一种就是由前端直接上传到华为云obs,特此记录一下。

1.官方文档 里面下载需要用到的sdk,如下图:

image.png

官方文档推荐npm安装(做完才发现就懒得改了,作者使用的是源码安装)

image.png

2.下载解压后放到静态文件中引入

image.png

3.初始化,创建obsClient 实例

// 创建ObsClient实例
var obsClient = new ObsClient({
    access_key_id: '*** Provide your Access Key ***',       
    secret_access_key: '*** Provide your Secret Key ***',
    // 这里以华北-北京四为例,其他地区请按实际情况填写
    server: 'https://obs.cn-north-4.myhuaweicloud.com'
    
});

4.上传文件

obsClient.putObject({
       Bucket: 'bucketname',
       Key: 'objectname',
       SourceFile: document.getElementById('input-file').files[0]
}, function (err, result) {
       if(err){
              console.error('Error-->' + err);
       }else{
              console.log('Status-->' + result.CommonMsg.Status);
       }
});

image.png

5.下载文件

obsClient.getObject({
       Bucket : 'bucketname',
       Key : 'objectname',
       SaveByType : 'file'
}, function (err, result) {
       if(err){
              console.error('Error-->' + err);
       }else{
              console.log('Status-->' + result.CommonMsg.Status);
              if(result.CommonMsg.Status < 300 && result.InterfaceResult){
                   // 获取下载对象的路径
                   console.log('Download Path:'); 
                   console.log(result.InterfaceResult.Content.SignedUrl); 
              }
       }
});

image.png

6.删除文件

obsClient.deleteObject({
       Bucket : 'bucketname',
       Key : 'objectname'
}, function (err, result) {
       if(err){
              console.error('Error-->' + err);
       }else{
              console.log('Status-->' + result.CommonMsg.Status);
       }
});

还有很多操作,如上传进度条,分段上传、断点续传等功能就直接参考 官方文档

以上仅此记录,如有错误欢迎指正。