阿里云文档地址:https://help.aliyun.com/document_detail/31926.html
本文仅有服务端签名后直传。 私有bucket下,文件下载见下一篇博 https://ygstriver.blog.csdn.net/article/details/121657880

1.阿里云OSS控制台

创建私有bucket

打开阿里云OSS控制台,创建bucket。(公共读写更简单,私有可以防止其他人获取你的文件,避免数据泄漏或者流量消耗)
在这里插入图片描述

创建子账户

进入RAM控制台,创建子用户。
请添加图片描述
勾选Open API调用访问
然后添加权限AliyunOSSFullAccess

开启跨域

在bucket页面,开启跨域!在这里插入图片描述

2.服务端代码

导入依赖

        <!--        阿里云oss-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alicloud-oss</artifactId>
            <version>2.2.0.RELEASE</version>
        </dependency>

policy()接口

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.ruoyi.common.core.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController //就是普通的Controller 再加 将响应体以json格式返回  即@ResponseBody
public class OssController {

    @Autowired
    OSS ossClient;

    @Value("${spring.cloud.alicloud.oss.endpoint}")  //@Value 在nacos之前获取,所有写配置中心的话这个不能注入
    private String endpoint;
    @Value("${spring.cloud.alicloud.oss.bucket}")
    private String bucket;
    @Value("${spring.cloud.alicloud.access-key}")
    private String accessId;

    @RequestMapping("/xxx/xxx")
    public AjaxResult policy(){
        String host = "https://" + bucket + "." + endpoint; // host的格式为 bucketname.endpoint
        // callbackUrl为上传回调服务器的URL,请将下面的IP和Port配置为您自己的真实信息。
//        String callbackUrl = "http://88.88.88.88:8888";
        String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String dir = format + "/"; // 用户上传文件时指定的前缀。

        Map<String, String> respMap = null;
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            // PostObject请求最大可支持的文件大小为5 GB,即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);
            respMap = new LinkedHashMap<>();
            respMap.put("accessid", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
            // respMap.put("expire", formatISO8601Date(expiration));
        } catch (Exception e) {
            // Assert.fail(e.getMessage());
            System.out.println(e.getMessage());
        } finally {
            ossClient.shutdown();
        }
        return AjaxResult.success().put("data",respMap);
    }
}

AjaxResult是统一返回结构,也可以直接返回Map,反正你能得到这个就行了

3.前端代码:

采用vue框架
①上传表单,这里用了element UI 自行导入即可

<el-upload
            ref="upload"
            :limit="1"
            :data="dataObj"
            accept=".ppt, .pptx"
            :action="upload.url"
            :headers="upload.headers"
            :file-list="upload.fileList"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="false"
          >
            <el-button slot="trigger" size="small" type="primary" @click="beforeUpload"
              >选取文件</el-button
            >
            <el-button
              style="margin-left: 10px"
              size="small"
              type="success"
              :loading="upload.isUploading"
              @click="submitUpload"
              >上传到服务器</el-button
            >
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件,且不超过500kb
            </div>
          </el-upload>

② 数据参数

	//签名参数
      dataObj: {
        policy: "",
        signature: "",
        key: "",
        ossaccessKeyId: "",
        dir: "",
        host: "",
        // callback:'',
      },
      // 上传参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        //设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        //上传的地址
        url: "你的Bucket 域名http://xxx.oss-cn-xxxx.aliyuncs.com/",
        //上传的文件列表
        fileList: [],
      },

③请求方法

 /**
     * 图片上传前先获取policy
     */
    beforeUpload(file) {
      let _self = this;
      //console.log("图片上传前先获取policy");
      getPolicy().then((response) => {
        //console.log("response:", response);
        _self.dataObj.policy = response.data.policy;
        _self.dataObj.signature = response.data.signature;
        _self.dataObj.ossaccessKeyId = response.data.accessid;
        _self.dataObj.key = response.data.dir + getUUID() + "_${filename}";
        _self.dataObj.dir = response.data.dir;
        _self.dataObj.host = response.data.host;
       // console.log("响应的数据222。。。", _self.dataObj);
      });
    },

    handleUpdate(row) {
      this.upload.fileList = [
        { name: this.form.fileName, url: this.form.filePath },
      ];
    },
    // 文件提交处理
    submitUpload() {
      this.$refs.upload.submit();
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      this.form.filePath = response.url;
      this.$modal.msgSuccess(response.msg);
    },

以下方法写在单独的一个api.js中,引入即可

// 获取阿里云上传policy
export function getPolicy() {
  return request({
    url: '你的policy接口',
    method: 'get',
  })
}

/**
 * 获取uuid
 */
 export function getUUID () {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
  })
}

报错排坑

1.上传阿里云oss,报跨域错误, 记得bucket开启跨域
2.报400错误,可以查看请求返回信息,可能是上传和获取policy时顺序不对,或者上传速度太快,policy的参数还没变就传上去了。


有其他问题,欢迎大家留言讨论。
Logo

前往低代码交流专区

更多推荐