SpringBoot+OSS实现文件上传

创建spring boot项目

pom依赖

xml 复制代码
 <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.17.4</version>
        </dependency>
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.1</version>
        </dependency>
        <dependency>
            <groupId>javax.activation</groupId>
            <artifactId>activation</artifactId>
            <version>1.1.1</version>
        </dependency>
        <!-- no more than 2.3.3-->
        <dependency>
            <groupId>org.glassfish.jaxb</groupId>
            <artifactId>jaxb-runtime</artifactId>
            <version>2.3.3</version>
        </dependency>

yaml配置文件

application.yaml

yaml 复制代码
server:
  port: 8089
spring:
  profiles:
    active: dev
alioss:
  endpoint: ${alioss.endpoint}
  accessKeyId: ${alioss.accessKeyId}
  accessKeySecret: ${alioss.accessKeySecret}
  bucketName: ${alioss.bucketName}

application-dev.yaml

yaml 复制代码
alioss:
  endpoint: oss-cn-beijing.aliyuncs.com
  accessKeyId: 写自己的keyId
  accessKeySecret: 写自己的密钥
  bucketName: 写自己的bucketName

文件上传工具类

java 复制代码
package com.pkq.demo.utils;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * ClassName: AliOSSUtils
 * Package: com.pkq.demo.utils
 * Description:
 *
 * @Author pkq
 * @Create 2024-07-05 15:09
 * @Version 1.0
 */
@Component
@Slf4j
public class AliOSSUtils {
    @Value("${alioss.endpoint}")
    private String endpoint;
    @Value("${alioss.accessKeyId}")
    private String accessKeyId;
    @Value("${alioss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${alioss.bucketName}")
    private String bucketName;
    /**
     * 实现上传图片到OSS
     */
    public String upload(MultipartFile multipartFile) throws IOException {
        // 获取上传的文件的输入流
        InputStream inputStream = multipartFile.getInputStream();

        // 避免文件覆盖
        String originalFilename = multipartFile.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

        //上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, fileName, inputStream);

        //文件访问路径
        String url ="https://" + bucketName + "." + endpoint + "/" + fileName;

        // 关闭ossClient
        ossClient.shutdown();
        return url;// 把上传到oss的路径返回
    }
}

通用返回结果类

java 复制代码
package com.pkq.demo.result;

import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * ClassName: Result
 * Package: com.pkq.demo.result
 * Description:
 *
 * @Author pkq
 * @Create 2024-07-05 15:23
 * @Version 1.0
 */
@Data
@NoArgsConstructor
public class Result<T> {
    private Integer code;
    private String message;
    private T data;
    public Result(T data) {
        this(200,null,data);
    }
    public Result(int code, String message) {
        this(code,message,null);
    }
    public Result(int code, String message,T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }


    public static <T> Result<T> success(T data) {
        return new Result<>(data);
    }

    public static <T> Result<T> fail(String message) {
        return new Result<>(500, message);
    }

    public static <T> Result<T> fail(int code, String message) {
        return new Result<>(code, message);
    }
}

文件上传接口

java 复制代码
package com.pkq.demo.controller;

import com.pkq.demo.result.Result;
import com.pkq.demo.utils.AliOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * ClassName: UploadController
 * Package: com.pkq.demo.controller
 * Description:
 *
 * @Author pkq
 * @Create 2024-07-05 15:27
 * @Version 1.0
 */
@Slf4j
@RestController
public class UploadController {

    @Autowired
    private AliOSSUtils aliOSSUtils;

    @PostMapping("/upload")
    public Result<String> upload(MultipartFile image) throws IOException {
        //调用阿里云OSS工具类,将上传上来的文件存入阿里云
        String url = aliOSSUtils.upload(image);
        //将图片上传完成后的url返回,用于浏览器回显展示
        return Result.success(url);
    }

}

测试

相关推荐
魔道不误砍柴功1 小时前
Java 中如何巧妙应用 Function 让方法复用性更强
java·开发语言·python
NiNg_1_2341 小时前
SpringBoot整合SpringSecurity实现密码加密解密、登录认证退出功能
java·spring boot·后端
闲晨1 小时前
C++ 继承:代码传承的魔法棒,开启奇幻编程之旅
java·c语言·开发语言·c++·经验分享
种树人202408191 小时前
如何在 Spring Boot 中启用定时任务
spring boot
Chrikk3 小时前
Go-性能调优实战案例
开发语言·后端·golang
幼儿园老大*3 小时前
Go的环境搭建以及GoLand安装教程
开发语言·经验分享·后端·golang·go
canyuemanyue3 小时前
go语言连续监控事件并回调处理
开发语言·后端·golang
杜杜的man3 小时前
【go从零单排】go语言中的指针
开发语言·后端·golang
测开小菜鸟3 小时前
使用python向钉钉群聊发送消息
java·python·钉钉
P.H. Infinity4 小时前
【RabbitMQ】04-发送者可靠性
java·rabbitmq·java-rabbitmq