阿里云OSS前端直传(Browser.js)

Browser.js安装

安装依赖包或引入js文件:

npm install ali-oss

npm install uuid

          <el-upload
            class="upload-demo"
            drag
            :file-list="fileList1"
            action=""
            :http-request="handleUpload"
            multiple>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传jpg/png文件,且不超过500kb</div>
          </el-upload>    

          handleUpload(op) {
            oss.bucketUpload(op.file,
              (res) => {
                console.log(res);
              });
          },
          handlePreview(path) {
            oss.bucketPreview(path,
             (res) => {
             console.log(res)
             })
         }
import {getUploadVoucher} from "@/api/oss";
// uuidv4
import {v4 as uuidv4} from 'uuid';
import path from "path";

const OSS = require('ali-oss')
export default {
  /**
   * 阿里云oss sdk文件上传  dir 上传到的文件位置
   * @param {*} file 文件流
   * @param {*} successCallback 成功回调
   * @param {*} errCallBack 失败回调
   * @param {*} dir 上传文件夹路径  譬如images
   */

  bucketUpload(file, successCallback = new Function(), dir = 'zlProcess') {
    let fileName = file.name// 先获取上传要的资料签名
    // 后台接口
    getUploadVoucher().then((res) => {
        if (res.code === 200) {
          let obj = res.data.credentials || {}
          // 实例化一个上传客户端
          const client = new OSS({
            // yourRegion填写Bucket所在地域。以华东1(杭州)为例,yourRegion填写为oss-cn-hangzhou。
            region: 'oss-cn-hangzhou',
            // 从STS服务获取的临时访问密钥(AccessKey ID和AccessKey Secret)。
            accessKeyId: obj.accessKeyId,
            accessKeySecret: obj.accessKeySecret,
            // 从STS服务获取的安全令牌(SecurityToken)。
            stsToken: obj.securityToken,
            // 填写Bucket名称。
            bucket: 'zl-process',
          })
          try {
            // 填写Object完整路径。Object完整路径中不能包含Bucket名称。
            // 您可以通过自定义文件名(例如exampleobject.txt)或文件完整路径(例如exampledir/exampleobject.txt)的形式实现将数据上传到当前Bucket或Bucket中的指定目录。
            // data对象可以自定义为file对象、Blob数据或者OSS Buffer。
            let uuid = uuidv4() + "/" + fileName;
            if (dir.substring(dir.length - 1, 1) !== '/') {
              dir += '/'
            }
            const result = client.put(dir + uuid, file);
            result.then(res => {
              // let size = file.size > 1000000 ? parseFloat(file.size / 1000000).toFixed(2) + 'M' : parseFloat(file.size / 1000).toFixed(2) + 'KB'
              successCallback({
                name: res.name,
                url: res.url
              })
            })
          } catch (e) {
            console.log(e)
          }
        } else {
          this.$message.warning("获取STSToken失败");
        }
      }
    );
  },

  bucketPreview(path, successCallback = new Function()) {
    getUploadVoucher().then((res) => {
      if (res.code === 200) {
        let obj = res.data.credentials || {}
        // 实例化一个上传客户端
        const client = new OSS({
          // yourRegion填写Bucket所在地域。以华东1(杭州)为例,yourRegion填写为oss-cn-hangzhou。
          region: 'oss-cn-hangzhou',
          // 从STS服务获取的临时访问密钥(AccessKey ID和AccessKey Secret)。
          accessKeyId: obj.accessKeyId,
          accessKeySecret: obj.accessKeySecret,
          // 从STS服务获取的安全令牌(SecurityToken)。
          stsToken: obj.securityToken,
          // 填写Bucket名称。
          bucket: 'zl-process',
        });
        const url = client.signatureUrl(path, {
          // 如果您希望生成的签名URL可以应用图片样式的效果,您可以通过process参数指定样式,格式为style/样式名称。
          // process: "style/imagestyle",
        });
        // 设置URL的有效时长。单位为秒。如果不设置有效时长,则默认为1800。
        // url = client.signatureUrl('example.jpg', {expires: 3600});
        // console.log(url);
        successCallback({
          url: url
        })
      }
    })
  }
}

 

  1. 客户端向业务服务器请求上传策略。

    客户端首先向业务服务器发送请求,请求中应包含所需上传操作的最小权限需求(例如上传到特定Bucket的权限)和期望的有效时间等信息。不同于直接请求Post签名和Post Policy,客户端需要请求的是一个带有特定权限限制的STS Token以及上传策略。

  2. 业务服务器向STS服务请求获取STS Token。

    业务服务器收到客户端请求后,使用长期凭证向阿里云STS服务发起请求,生成一个具有限定权限和有效时间的STS Token。

  3. STS服务向业务服务器返回STS Token。

  4. 业务服务器根据STS Token和其他上传限制生成上传策略。

    业务服务器根据返回的STS Token和其他上传限制条件(例如Bucket名称、目录路径、过期时间等)生成一个安全的上传策略(Policy),并返回给客户端。

  5. 客户端构造并提交表单上传请求。

    客户端使用收到的STS Token和上传策略,结合文件信息构造HTML表单。此时,上传策略中的签名和STS Token的加入使得客户端可以直接与OSS交互,而无需暴露业务服务器的长期凭证。

  6. OSS返回成功响应给客户端。

引入pom依赖包:
<!--阿里云oss 2.5.0-->
<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>3.5.0</version>
</dependency>

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-core</artifactId>
    <version>4.5.0</version>
</dependency>
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>cloudauth20221125</artifactId>
    <version>1.1.1</version>
</dependency>

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
    <version>1.1.0</version>
</dependency>
package com.process.web.controller.common;

import com.aliyun.sts20150401.models.AssumeRoleResponse;
import com.aliyun.tea.TeaException;
import com.process.common.core.controller.BaseController;
import com.process.common.core.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author
 * @title
 * @description
 * @updateTime 2024/7/19 9:41
 * @throws
 */
@RestController
@RequestMapping("/api/aliyun")
public class ApiAliyunController extends BaseController {

    @Value("${oss.aliyunAccessKeyId}")
    private String aliyunAccessKeyId;

    @Value("${oss.aliyunAccessKeySecret}")
    private String aliyunAccessKeySecret;

    /**
     * <b>description</b> :
     * <p>使用AK&amp;SK初始化账号Client</p>
     *
     * @return Client
     * @throws Exception
     */
    public com.aliyun.sts20150401.Client createClient() throws Exception {
        // 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        // 建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378657.html。
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId(aliyunAccessKeyId)
                // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret(aliyunAccessKeySecret);
        // Endpoint 请参考 https://api.aliyun.com/product/Sts
        config.endpoint = "sts.cn-hangzhou.aliyuncs.com";
        return new com.aliyun.sts20150401.Client(config);
    }

    /**
     * 获取oss  STS Token
     *
     * @return
     */
    @GetMapping("/getStsToken")
    @ResponseBody
    public AjaxResult getStsToken() {
        com.aliyun.sts20150401.Client client = null;
        try {
            client = createClient();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        com.aliyun.sts20150401.models.AssumeRoleRequest assumeRoleRequest = new com.aliyun.sts20150401.models.AssumeRoleRequest()
                .setRoleArn("acs:ram::1********:role/r*******")
                .setRoleSessionName("a****");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            AssumeRoleResponse assumeRoleResponse = client.assumeRoleWithOptions(assumeRoleRequest, runtime);
            Integer statusCode = assumeRoleResponse.statusCode;
            if (200 == statusCode) {
//                System.out.println(assumeRoleResponse);
                return AjaxResult.success(assumeRoleResponse.body);
            }
        } catch (TeaException error) {
            // 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return AjaxResult.error();
    }
}

  • 10
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值