文章目录
- springboot整合七牛云oss操作文件
- 核心代码(记得修改application.yml配置参数⭐)
- maven依赖
- QiniuOssProperties配置类
- UploadController
- ResponseResult统一封装响应结果
- ResponseType响应类型枚举
- OssUploadService接口
- QiniuOssUploadServiceImpl实现类
- QiniuOssApplication启动类
- application.yml
- 文件/图片上传(数据流方式上传)⭐
- 获取accessKey和secretKey配置内容
- 创建一个存储空间和获取bucket(存储空间名称)、服务器域名
- 文件删除⭐
springboot整合七牛云oss操作文件
核心代码(记得修改application.yml配置参数⭐)
maven依赖
<?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"><modelVersion>4.0.0</modelVersion><groupId>org.example</groupId><artifactId>qiniuOss</artifactId><version>1.0-SNAPSHOT</version><properties><!-- springboot版本--><spring-boot.version>2.7.2</spring-boot.version><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></properties><dependencyManagement><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>${spring-boot.version}</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><dependencies><!--实现自定义的properties(@ConfigurationProperties注解下的内容)可以在application.yml出现提示。导入了这个依赖,当我们运行项目后就会在target目录下面自动生成/META-INF/spring-configuration-metadata.json文件--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency><!-- springboot-web--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- String工具类包 --><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.12.0</version></dependency><!-- lombok--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.24</version></dependency>
<!-- 七牛云oss sdk--><dependency><groupId>com.qiniu</groupId><artifactId>qiniu-java-sdk</artifactId><version>[7.7.0, 7.10.99]</version></dependency><dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId><version>2.8.5</version><scope>compile</scope></dependency></dependencies></project>
QiniuOssProperties配置类
package com.boot.config;import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;/*** 七牛云oss配置类* @author youzhengjie 2022-10-07 18:07:19*/
@Component
@Data
@ConfigurationProperties(prefix = "qiniu")
@EnableConfigurationProperties({QiniuOssProperties.class
})
public class QiniuOssProperties {/*** 下面的AK、SK都要从七牛云的密钥管理中获取*/private String accessKey;private String secretKey;/*** 指定存储空间名称*/private String bucket;/*** 七牛云图片服务器域名(有效期30天,过期可以重新创建新的存储空间)*/private String ossUrl;
}
UploadController
package com.boot.controller;import com.boot.data.ResponseResult;
import com.boot.service.OssUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;/*** @author youzhengjie 2022-10-07 18:08:18*/
@RestController
public class UploadController {@Autowired@Qualifier("qiniuOssUploadServiceImpl") //指定spring注入的实现类为七牛云oss实现类private OssUploadService ossUploadService;/*** 图片上传* @param imageFile* @return*/@PostMapping(path = "/imageUpload")public ResponseResult imageUpload(MultipartFile imageFile){return ossUploadService.imageUpload(imageFile);}/*** 文件删除* @return*/@DeleteMapping(path = "/fileDelete")public ResponseResult fileDelete(String fileFullName){return ossUploadService.fileDelete(fileFullName);}}
ResponseResult统一封装响应结果
package com.boot.data;import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;/*** 统一响应结果*/
@JsonInclude(JsonInclude.Include.NON_NULL) //为null的字段不进行序列化
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ResponseResult<T> {/*** 响应状态码*/private Integer code;/*** 响应状态码对应的信息提示*/private String msg;/*** 返回给前端的数据*/private T data;public ResponseResult(Integer code, String msg) {this.code = code;this.msg = msg;}public ResponseResult(Integer code, T data) {this.code = code;this.data = data;}}
ResponseType响应类型枚举
package com.boot.enums;/*** 响应类型枚举类* @author youzhengjie 2022-09-22 22:47:21*/
public enum ResponseType {/*** 响应类型*/IMAGE_UPLOAD_SUCCESS(901,"图片上传成功"),IMAGE_UPLOAD_ERROR(902,"图片上传失败"),FILE_FORMAT_UNSUPPORT(903,"不支持该文件格式,上传失败"),FILE_DELETE_SUCCESS(904,"文件删除成功"),FILE_DELETE_ERROR(905,"文件删除失败"),;private int code;private String message;ResponseType(int code, String message) {this.code = code;this.message = message;}public int getCode() {return code;}public void setCode(int code) {this.code = code;}public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}
}
OssUploadService接口
package com.boot.service;import com.boot.data.ResponseResult;
import com.boot.enums.ResponseType;
import org.springframework.web.multipart.MultipartFile;/*** oss上传service接口* @author youzhengjie 2022-10-06 23:13:28*/
public interface OssUploadService {/*** oss图片上传* @param imageFile* @return 上传结果*/ResponseResult imageUpload(MultipartFile imageFile);/*** oss文件删除* @param fileFullName 文件全名,也就是下面这个代码生成的名字(记住不要加上域名),例如:* String newFileName = new StringBuilder()* .append(fileDir)* .append(uuidFileName)* .append(fileSuffix).toString();** @return 删除结果*/ResponseResult fileDelete(String fileFullName);}
QiniuOssUploadServiceImpl实现类
package com.boot.service.impl;import com.boot.config.QiniuOssProperties;
import com.boot.data.ResponseResult;
import com.boot.enums.ResponseType;
import com.boot.service.OssUploadService;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;/*** 七牛云oss文件上传实现类* @author youzhengjie 2022-10-06 23:14:17*/
@Service("qiniuOssUploadServiceImpl")
@Slf4j
public class QiniuOssUploadServiceImpl implements OssUploadService {@Autowiredprivate QiniuOssProperties qiniuOssProperties;/*** 检查文件是否是图片类型* @param originalFilename* @return true代表是图片,false则不是图片*/private boolean isImage(String originalFilename){//将文件名全部变小写String lowerOriginalFilename = originalFilename.toLowerCase();return lowerOriginalFilename.endsWith(".jpg") ||lowerOriginalFilename.endsWith(".png") ||lowerOriginalFilename.endsWith(".jpeg");}@Overridepublic ResponseResult imageUpload(MultipartFile imageFile) {//获取上传前的文件原名String oldFileName = imageFile.getOriginalFilename();//封装响应结果ResponseResult<Object> result = new ResponseResult<>();//如果不是图片则直接返回if(!isImage(oldFileName)){result.setCode(ResponseType.FILE_FORMAT_UNSUPPORT.getCode());result.setMsg(ResponseType.FILE_FORMAT_UNSUPPORT.getMessage());return result;}//构造一个带指定自动的Region对象的配置类Configuration cfg = new Configuration(Region.autoRegion());cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本UploadManager uploadManager = new UploadManager(cfg);//以日期作为目录,每一天的图片都会放到不同的目录下,方便管理SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/");String fileDir = simpleDateFormat.format(new Date());//UUID文件名String uuidFileName = UUID.randomUUID().toString().replaceAll("-", "");//获取文件后缀名 .jpgString fileSuffix= oldFileName.substring(oldFileName.lastIndexOf("."));//上传到oss中的新的图片文件名String newFileName = new StringBuilder().append(fileDir).append(uuidFileName).append(fileSuffix).toString();try {//获取前端传来的文件流InputStream inputStream = imageFile.getInputStream();Auth auth = Auth.create(qiniuOssProperties.getAccessKey(), qiniuOssProperties.getSecretKey());String upToken = auth.uploadToken(qiniuOssProperties.getBucket());//七牛云oss上传文件的核心方法Response response = uploadManager.put(inputStream,newFileName,upToken,null, null);result.setCode(ResponseType.IMAGE_UPLOAD_SUCCESS.getCode());result.setMsg(ResponseType.IMAGE_UPLOAD_SUCCESS.getMessage());//返回一个外面可以访问的图片地址。拼接域名+新的图片全路径,这样我们通过这个路径就可以直接在外面访问图片了result.setData(qiniuOssProperties.getOssUrl()+newFileName);return result;}catch (Exception e){e.printStackTrace();result.setCode(ResponseType.IMAGE_UPLOAD_ERROR.getCode());result.setMsg(ResponseType.IMAGE_UPLOAD_ERROR.getMessage());return result;}}/*** 七牛云oss文件删除* @param fileFullName 文件全名,也就是下面这个代码生成的名字(记住不要加上域名):* String newFileName = new StringBuilder()* .append(fileDir)* .append(uuidFileName)* .append(fileSuffix).toString();* @return 删除结果*/@Overridepublic ResponseResult fileDelete(String fileFullName) {//封装响应结果ResponseResult<Object> result = new ResponseResult<>();//构造一个带指定 Region 对象的配置类Configuration cfg = new Configuration(Region.autoRegion());Auth auth = Auth.create(qiniuOssProperties.getAccessKey(), qiniuOssProperties.getSecretKey());BucketManager bucketManager = new BucketManager(auth, cfg);try {//七牛云oss文件删除核心方法Response response = bucketManager.delete(qiniuOssProperties.getBucket(), fileFullName);result.setCode(ResponseType.FILE_DELETE_SUCCESS.getCode());result.setMsg(ResponseType.FILE_DELETE_SUCCESS.getMessage());return result;} catch (QiniuException ex) {ex.printStackTrace();result.setCode(ResponseType.FILE_DELETE_ERROR.getCode());result.setMsg(ResponseType.FILE_DELETE_ERROR.getMessage());return result;}}
}
QiniuOssApplication启动类
package com.boot;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class QiniuOssApplication {public static void main(String[] args) {SpringApplication.run(QiniuOssApplication.class,args);}}
application.yml
server:port: 8231
spring:servlet:#文件上传配置multipart:max-file-size: 3MBmax-request-size: 6MB#七牛云oss配置
qiniu:# 密钥管理的AKaccessKey: xPu-62ptMpg-kolm4nPVcvWgUnK1EZgu27ffKpBE#密钥管理的SKsecretKey: gDxkqTu7i7BBgbsvoQ7h4bmE5m16aRyHXyQ1Zc6D#指定我们文件上传的存储空间名称bucket: java-qiniu# 七牛云图片服务器域名(有效期30天,过期可以重新创建新的存储空间)ossUrl: http://rjc4vwz0g.hn-bkt.clouddn.com/
文件/图片上传(数据流方式上传)⭐
获取accessKey和secretKey配置内容
- 登录七牛云并进入下面的网址:
七牛云网址
创建一个存储空间和获取bucket(存储空间名称)、服务器域名
- 1:进入七牛云控制面板:
七牛云网址
- 2:创建新的存储空间:
- 3:查看刚刚创建的存储空间:
- 4:获取我们的存储空间域名
- 5:上传操作。由于我们后端进行了特殊校验,只允许传入图片,下面演示:
文件删除⭐
- 1:获取文件的key:
- 2:文件删除: