6.oss

我的域名--oss-cn-guangzhou.aliyuncs.com

上传数据

依赖

      <!--OSS SDK-->
        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.10.2</version>
        </dependency>

获得accessKey

 

 添加权限

 

 代码上传:(后端直传)

    @Test
    void uploadOSS() throws FileNotFoundException {
        String endpoint = "oss-cn-guangzhou.aliyuncs.com";

        // 云账号AccessKey有所有API访问权限,建议遵循阿里云安全最佳实践,创建并使用RAM子账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建。
        // 1. 创建RAM 子账户
        // 2. 获得accessKeyId  accessKeySecret
        // 3. 给子用户设置权限
        String accessKeyId = "LTAI5tRS8LDesCGoz7GBi6uv";
        String accessKeySecret = "E1OWlDShvCRM9O5bXOF6MRngDM5d17";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dir = simpleDateFormat.format(new Date())+"/";


        // 上传文件流。
        InputStream inputStream = new FileInputStream("D:\\JavaCode\\490javacode\\222.jpg");
        //bucket的名称
        ossClient.putObject("mall-xiaowu", dir+"222.jpg", inputStream);

        // 关闭OSSClient。
        ossClient.shutdown();

        System.out.println("上传成功!");
    }

 

 

 

 

 

 后端的准备工作:

@RestController
public class OSSController {

    @CrossOrigin//跨域支持
    @RequestMapping("/oss/policy")
    public Map<String,String> policy(){
        String accessId = "LTAI5tRS8LDesCGoz7GBi6uv"; // 请填写您的AccessKeyId。
        String accessKey = "E1OWlDShvCRM9O5bXOF6MRngDM5d17"; // 请填写您的AccessKeySecret。
        String endpoint = "oss-cn-guangzhou.aliyuncs.com"; // 请填写您的 endpoint。
        String bucket = "mall-xiaowu"; // 请填写您的 bucketname 。
        String host = "https://" + bucket + "." + endpoint; // host的格式为 bucketname.endpoint

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String date = simpleDateFormat.format(new Date());

        String dir = "tuling-test/"+date+"/"; // 用户上传文件时指定的前缀。

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey);
        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);

            Map<String, String> respMap = new LinkedHashMap<String, String>();
            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));
            return respMap;
        } catch (Exception e) {
            // Assert.fail(e.getMessage());
            System.out.println(e.getMessage());
        } finally {
            ossClient.shutdown();
        }
        return null;
    }
}

 

 后续只需要在前端拿到这些参数去进行post请求就行了

需要使用ElementUi

安装elementUi

 

在main.js中引入

 

 

一个独立的组件需要有以下三个解构,分别属于html,javascript,css

 

 由于不是url访问的组件所以不需要在route里面声明

 vue有很多诡异的缩进错误,这是官网的初始源代码

<template>
  <el-upload
    class="upload-demo"
    action="https://jsonplaceholder.typicode.com/posts/"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :file-list="fileList"
    list-type="picture"
  >
    <el-button size="small" type="primary">点击上传</el-button>
    <div slot="tip" class="el-upload__tip">
      只能上传jpg/png文件,且不超过500kb
    </div>
  </el-upload>
</template>

<script>
export default {
  data () {
    return {
      fileList: [
        {
          name: 'food.jpeg',
          url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
        }
      ]
    }
  },
  methods: {
    handleRemove (file, fileList) {
      console.log(file, fileList)
    },
    handlePreview (file) {
      console.log(file)
    }
  }
}
</script>
<style></style>

注册

 

 使用

 

 开启oss跨域设置

 

允许所有

 自己的代码

<template>
  <el-upload
    class="upload-demo"
    :action="objData.host"
    :file-list="fileList"
    :before-upload="ossPolicy"
    list-type="picture"
  >
    <el-button size="small" type="primary">点击上传</el-button>
    <div slot="tip" class="el-upload__tip">
      只能上传jpg/png文件,且不超过500kb
    </div>
  </el-upload>
</template>

<script>
export default {
  data () {
    return {
      fileList: [
        {
          name: 'food.jpeg',
          url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
        }
      ],
      objData: {
        OSSAccessKeyId: '',
        policy: '',
        Signature: '',
        key: '',
        host: '',
        dir: ''
      }
    }
  },
  methods: {
    ossPolicy (file) {
      let _self = this
      return new Promise((resolve, reject) => {
        this.axios.get('http://localhost:8088/oss/policy')
          .then(response => {
            _self.objData.OSSAccessKeyId = response.data.accessid
            _self.objData.policy = response.data.policy
            _self.objData.Signature = response.data.signature
            _self.objData.dir = response.data.dir
            _self.objData.host = response.data.host
            _self.objData.key = response.data.dir + '$filename}'
            resolve(true)
          })
          .catch(function (error) {
            console.log(error)
          })
      })
    }
  }
}
</script>
<style></style>

 

posted @ 2021-07-31 12:02  一拳超人的逆袭  阅读(325)  评论(0)    收藏  举报