Front end: vue

Single file upload component

<template> 
  <div>
    <el-upload
      action="https://codingce-product.oss-cn-beijing.aliyuncs.com"
      :data="dataObj"
      list-type="picture"
      :multiple="false" :show-file-list="showFileList"
      :file-list="fileList"
      :before-upload="beforeUpload"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :on-preview="handlePreview">
      <el-button size="small" type="primary">Click on the upload</el-button>
      <div slot="tip" class="el-upload__tip">Only JPG/PNG files can be uploaded, and the maximum size is 10MB</div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="fileList[0].url" alt="">
    </el-dialog>
  </div>
</template>
<script>
   import {policy} from './policy'
   import { getUUID } from '@/utils'

  export default {
    name: 'singleUpload'.props: {
      value: String
    },
    computed: {
      imageUrl() {
        return this.value;
      },
      imageName() {
        if (this.value ! =null && this.value ! = =' ') {
          return this.value.substr(this.value.lastIndexOf("/") + 1);
        } else {
          return null; }},fileList() {
        return [{
          name: this.imageName,
          url: this.imageUrl
        }]
      },
      showFileList: {
        get: function () {
          return this.value ! = =null && this.value ! = =' '&& this.value! = =undefined;
        },
        set: function (newValue) {}}},data() {
      return {
        dataObj: {
          policy: ' '.signature: ' '.key: ' '.ossaccessKeyId: ' '.dir: ' '.host: ' '.// callback:'',
        },
        dialogVisible: false
      };
    },
    methods: {
      emitInput(val) {
        this.$emit('input', val)
      },
      handleRemove(file, fileList) {
        this.emitInput(' ');
      },
      handlePreview(file) {
        this.dialogVisible = true;
      },
      beforeUpload(file) {
        let _self = this;
        return new Promise((resolve, reject) = > {
          policy().then(response= > {
            console.log("Response data",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("Response data 222...",_self.dataObj);
            resolve(true)
          }).catch(err= > {
            reject(false)})})},handleUploadSuccess(res, file) {
        console.log("Upload successful...")
        this.showFileList = true;
        this.fileList.pop();
        this.fileList.push({name: file.name, url: this.dataObj.host + '/' + this.dataObj.key.replace("${filename}",file.name) });
        this.emitInput(this.fileList[0].url); }}}</script>
<style>

</style>
Copy the code

HTTP Request encapsulation

import http from '@/utils/httpRequest.js'
export function policy() {
    return new Promise((resolve, reject) = > {
        http({
            url: http.adornUrl("/thirdparty/oss/polcy"),
            method: "get".params: http.adornParams({})
        }).then(({ data }) = >{ resolve(data); })}); }Copy the code

The back-end SpringBoot

Guide package problem see here: solution

pom


      
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1. RELEASE</version>
        <relativePath/> <! -- lookup parent from repository -->
    </parent>
    <groupId>cn.com.codingce</groupId>
    <artifactId>gulimall-third-party</artifactId>
    <version>0.0.1 - the SNAPSHOT</version>
    <name>gulimall-third-party</name>
    <description>Third Party services</description>
    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Hoxton.RELEASE</spring-cloud.version>
    </properties>
    <dependencies>
        <! -- Public Project
        <dependency>
            <groupId>cn.com.codingce</groupId>
            <artifactId>gulimall-common</artifactId>
            <version>0.0.1 - the SNAPSHOT</version>
            <! -- Exclude package -->
            <exclusions>
                <exclusion>
                    <groupId>com.baomidou</groupId>
                    <artifactId>mybatis-plus-boot-starter</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <! - introduction of spring - the cloud - starter - alicloud - oss - >
        <! 2.1.0RELEASE stable version -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <! --<artifactId>aliyun-oss-spring-boot-starter</artifactId>-->
            <artifactId>spring-cloud-starter-alicloud-oss</artifactId>
            <version>2.1.0. RELEASE</version>
        </dependency>



    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2.2.2. RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>aliyun-oss-spring-boot-starter</artifactId>
                <version>1.0.0</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
Copy the code

OSS. Yml configuration

spring:
  application:
    name: gulimall-third-party

  cloud:
    nacos:
      discovery:
        server-addr: 127.0. 01.: 8848
    alicloud:
      access-key: "TAAAAAAAAAAAAAAAAAAAAAA"
      secret-key: "sJxQJEQBIdwadawdawdawfdawda5z"
      oss:
        endpoint: "oss-cn-beijing.aliyuncs.com"
        # this does not have this attribute, add it yourself
        bucket: "codingce-product"

logging:
  level:
    cn.com.codingce: debug

server:
  port: 30000
Copy the code

Controller

package cn.com.codingce.thirdparty.controller;

import cn.com.codingce.common.utils.R;
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 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;

/ * * *@author mxz
 */
@RestController
public class OssController {

    @Autowired
    OSS ossClient;

    @Value("${spring.cloud.alicloud.oss.endpoint}")
    private String endpoint;

    @Value("${spring.cloud.alicloud.oss.bucket}")
    private String bucket;

    @Value("${spring.cloud.alicloud.access-key}")
    private String accessId;

    @RequestMapping("/oss/polcy")
    public R polcy(a) {
        // String accessId = "
      
       "; // Please enter your AccessKeyId.
      
        // String accessKey = "
      
       "; // Please fill in your AccessKeySecret.
      
        // String endpoint = "oss-cn-hangzhou.aliyuncs.com"; // Please enter your endpoint.
        // String bucket = "codingce-product"; // Please enter your bucketname.
        String host = "https://" + bucket + "." + endpoint; // The host format is bucketname.endpoint
        // callbackUrl is the URL of the callback server. Please configure the following IP and Port as your own real information.
        / / String callbackUrl = "http://88.88.88.88:8888";
        String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        // String dir = "user-dir-prefix/"; // The prefix specified when the user uploads the file.
        String dir = format + "/"; // The prefix specified when the user uploads the file.

        // Create an OSSClient instance.
        // OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey);
        Map<String, String> respMap = null;
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            The maximum file size supported by PostObject request is 5 GB, that is, CONTENT_LENGTH_RANGE is 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<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));


        } catch (Exception e) {
            // Assert.fail(e.getMessage());
            System.out.println(e.getMessage());
        } finally {
            ossClient.shutdown();
        }
        return R.ok().put("data", respMap); }}Copy the code

Implementation effect

There are cross-domain problems with the front – and back-end separated projects

You can follow the steps given in the official documents The article has been uploaded:Gitee.com/codingce/he…

Project Address:Github.com/xzMhehe/cod…