阿里云OSS存储:

阿里云OSS存储:

官网的开发文档:

https://help.aliyun.com/document_detail/31926.html?spm=a2c4g.11186623.6.1371.32e958d58D8p2V

1、导入pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>leyou</artifactId>
        <groupId>com.leyou</groupId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>ly_upload</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--eureka客户端-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <dependency>
            <groupId>com.leyou</groupId>
            <artifactId>ly_common</artifactId>
            <version>1.0.0-SNAPSHOT</version>
        </dependency>
        <!--阿里云的oos-->
        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.4.2</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>

</project>
2、yml
server:
  port: 8082
spring:
  application:
    name: upload-service
  servlet:
    multipart:
      max-file-size: 5MB # 限制文件上传的大小
# Eureka
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:10086/eureka
  instance:
    ip-address: 127.0.0.1
    prefer-ip-address: true
    instance-id: ${eureka.instance.ip-address}:${server.port}
#自定义的
ly:
  oss:
    accessId:  accessId
    accessKey: accessKey
    endpoint: oss-cn-xxx.aliyuncs.com
    bucket: bucket-xx
    host: https://bucket-xx.oss-cn-xxx.aliyuncs.com  #  访问oss的域名,很重要bucket + endpoint
    dir: "" # 保存到bucket的某个子目录
    expireTime: 20 # 过期时间,单位是S
    maxFileSize: 5242880 #文件大小限制,这里是5M

3、启动类
package com.leyou;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

/**
 * @Author: swq
 * @Date: 2019/8/31  0:37
 */
@SpringBootApplication
@EnableDiscoveryClient
public class LyUploadApplication {
    public static void main(String[] args) {
        SpringApplication.run(LyUploadApplication.class,args);
    }
}

4、属性类
package com.leyou.upload.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @Author: swq
 * @Date: 2019/8/31  17:24
 */
@Data
@Component
@ConfigurationProperties("ly.oss")
public class OSSProperties {
    private String accessId;
    private String accessKey;
    private String endpoint;
    private String bucket;
    private String host;
    private String dir;
    private long expireTime;
    private long maxFileSize;
}

5、OSSConfig(替代 OSSClient client = new OSSClient(endpoint, accessId, accessKey))这个过时的方法的
package com.leyou.upload.config;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author: swq
 * @Date: 2019/8/31  17:57
 */
@Configuration
public class OSSConfig {
    @Bean
    public OSS ossClient(OSSProperties prop){
        return new OSSClientBuilder()
                .build(prop.getEndpoint(), prop.getAccessId(), prop.getAccessKey());
    }
}

6、Controller
package com.leyou.upload.controller;

import com.leyou.upload.service.UploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 * @Author: swq
 * @Date: 2019/8/31  0:44
 */
@RestController
public class UploadController {

    /**
     * 到应用服务器获取标签
     *
     * @return
     */
    @GetMapping("/signature")
    public ResponseEntity<Map<String, String>> signature() {
        return ResponseEntity.ok(uploadService.signature());
    }
}

7、service
package com.leyou.upload.service;

import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 * @Author: swq
 * @Date: 2019/8/31  0:48
 */
public interface UploadService {

    /**
     * 到本地服务器获取标签
     * @return
     */
    Map<String, String> signature();

}

8、serviceImpl
package com.leyou.upload.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.leyou.common.enums.LyExceptionEnums;
import com.leyou.common.exception.LyException;
import com.leyou.upload.config.OSSProperties;
import com.leyou.upload.service.UploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @Author: swq
 * @Date: 2019/8/31  0:49
 */
@Service
public class UploadServiceImpl implements UploadService {
    @Autowired
    private OSSProperties properties;
    @Autowired
    private OSS client;

    /**
     * 到本地服务器获取标签
     *
     * @return
     */
    @Override
    public Map<String, String> signature() {
        String accessId = properties.getAccessId(); // 请填写您的AccessKeyId。
        String accessKey = properties.getAccessKey(); // 请填写您的AccessKeySecret。
        String endpoint = properties.getEndpoint(); // 请填写您的 endpoint。
        String bucket = properties.getBucket(); // 请填写您的 bucketname 。
        String host = properties.getHost(); // host的格式为 bucketname.endpoint
        // callbackUrl为 上传回调服务器的URL,请将下面的IP和Port配置为您自己的真实信息。
        String callbackUrl = "";
        String dir = properties.getDir(); // 用户上传文件时指定的前缀。


        try {
            long expireTime = properties.getExpireTime();
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = client.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));
            // respMap.put("expire", formatISO8601Date(expiration));
            return respMap;

        } catch (Exception e) {
            e.printStackTrace();
            throw new LyException(LyExceptionEnums.FILE_UPLOAD_ERROR);
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值