首先先创建一个仓库
Spring Boot实现阿里云OSS文件上传1.png

首先创建一个用户AccessKey
Spring Boot实现阿里云OSS文件上传2.png
把仓库读写权限设置为公共读
Spring Boot实现阿里云OSS文件上传3.png
然后开始开发,引入pom坐标

<!-- Ali Cloud -->
<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>3.8.1</version>
    <exclusions>
        <exclusion>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>

编写DTO

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
 * 文件信息
 * <p>
 * Description:
 * </p>
 *
 * @author Lusifer
 * @version v1.0.0
 * @date 2019-08-26 07:25:28
 * @see com.funtl.myshop.plus.cloud.dto
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class FileInfo implements Serializable {
    /**
     * 文件路径
     */
    private String path;
}

编写Feign接口

/**
 * 文件上传
 * <p>
 * Description:
 * </p>
 *
 * @author songzixian
 * @version v1.0.0
 * @create 2020-02-10 0:38
 * @see com.songzixian.cloud.feign
 */
@FeignClient(value = "cloud-upload",path = "upload",configuration = FeignRequestConfiguration.class)
public interface UploadFeign {

    /**
     * 文件上传
     * @param multipartFile
     * @return
     */
    String upload(@RequestParam(value = "multipartFile")MultipartFile multipartFile);
}

编写Controller

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.songzixian.cloud.dto.FileInfo;
import com.songzixian.commons.dto.ResponseResult;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import sun.java2d.pipe.SpanIterator;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传服务
 * <p>
 * Description:
 * </p>
 *
 * @author songzixian
 * @version v1.0.0
 * @create 2020-02-10 12:27
 * @see com.songzixian.cloud.controller
 */
@RestController
@RequestMapping(value = "upload")
public class UploadController {

    //外网地址
    private static final String ENDPOINT = "oss-cn-shenzhen.aliyuncs.com";
    //AccessKey ID    
    private static final String ACCESS_KEY_ID = "LTAI4FqLipWEZ5hWL198qKos";
    //Access Key Secret    
    private static final String ACCESS_KEY_SECRET = "W51CzGrwKuMrWl6wUm4qyEfVdN6m3Z";
    //仓库名称
    private static final String BUCKET_NAME = "image-songzixian-com";


    /**
     * 文件上传
     * @param multipartFile
     * @return
     */
    @PostMapping(value = "")
    public ResponseResult<FileInfo> upload(MultipartFile multipartFile){
        System.out.println("multipartFile"+multipartFile);
        //获取原始名字
        String fileName = multipartFile.getOriginalFilename();
        System.out.println("fileName="+fileName);
        //截取
        String suffix = fileName.substring(fileName.lastIndexOf(",")+1);
        System.out.println("suffix"+suffix);
        String newName = UUID.randomUUID()+"."+suffix;

        System.out.println("newName="+newName);
        //构建OSS客户端
        OSS client = new OSSClientBuilder().build(ENDPOINT,ACCESS_KEY_ID,ACCESS_KEY_SECRET);

        try {
            //上传文件
            client.putObject(new PutObjectRequest(BUCKET_NAME,newName,new ByteArrayInputStream(multipartFile.getBytes())));
            // 上传文件路径 = http://BUCKET_NAME.ENDPOINT/自定义路径/fileName
            return new ResponseResult<FileInfo>(ResponseResult.CodeStatus.FAIL,"文件上传成功",new FileInfo("http://" + BUCKET_NAME + "." + ENDPOINT + "/" + newName));
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseResult<FileInfo>(ResponseResult.CodeStatus.FAIL,"文件上传失败,请重试" );
        }finally {
            client.shutdown();
        }
    }
}

编写application.yml

base:
  config:
    oauth:
      hostname: blog-business-usermanagement-service
      port: 9001
    nacos:
      hostname: 106.54.187.185
      port: 8848

spring:
  application:
    name: blog-business-usermanagement-service
  main:
    allow-bean-definition-overriding: true
  jackson:
    time-zone: GMT+8
    date-format: yyyy-MM-dd HH:mm:ss
  ## spring cloud alibaba
  cloud:
    nacos:
      discovery:
        server-addr: 106.54.187.185:8848

security:
  oauth2:
    client:
      client-id: client
      client-secret: secret
      access-token-uri: http://localhost:9001/oauth/token
      user-authorization-uri: http://localhost:9001/oauth/authorize
    resource:
      token-info-uri: http://localhost:9001/oauth/check_token

server:
  port: 10001
management:
  endpoints:
    web:
      exposure:
        include: "*"

测试上传
打开 PostMan,新增访问地址 http://localhost:10001/upload
增加 Headers 配置

KEY: Content-Type
VALUE: multipart/form-data

Spring Boot实现阿里云OSS文件上传4.png

Spring Boot实现阿里云OSS文件上传5.png

Last modification:February 10, 2020
如果觉得这篇技术文章对你有用,请随意赞赏