整合阿里的对象存储服务
这里就不教怎么去开启oss服务了,直接去阿里云官网找就是了
直接先看配置信息吧:
然后定义的配置类(单例模式):
package com.dwk.design.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* Description:
* 开发者相关配置信息
* @author: mushi
* @Date: 2021/2/2 9:28
*/
@Component
@ConfigurationProperties(prefix = "ali.config")
public class AliConfig {
private static volatile AliConfig aliConfig = null;
/**地域节点*/
private String endpoint;
/**账号*/
private String accessKeyId;
/**密码*/
private String accessKeySecret;
/**存储空间*/
private List<String> bucketName;
private AliConfig (){
}
public static AliConfig getAliConfig() {
if (aliConfig == null){
aliConfig = new AliConfig();
System.out.println(aliConfig.getAccessKeyId()+aliConfig.getEndpoint());
}
return aliConfig;
}
public String getEndpoint() {
return endpoint;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
public String getAccessKeyId() {
return accessKeyId;
}
public void setAccessKeyId(String accessKeyId) {
this.accessKeyId = accessKeyId;
}
public String getAccessKeySecret() {
return accessKeySecret;
}
public void setAccessKeySecret(String accessKeySecret) {
this.accessKeySecret = accessKeySecret;
}
public List<String> getBucketName() {
return bucketName;
}
public void setBucketName(List<String> bucketName) {
this.bucketName = bucketName;
}
}
下面贴一段上传文件的代码:
1、定义一个接收文件名、文件路径、文件类型的bean:
package com.dwk.design.bean;
import org.springframework.stereotype.Component;
/**
* Description:
*
* @author: mushi
* @Date: 2021/3/10 14:46
*/
@Component
public class FileBean {
/**文件名*/
private String fileName;
/**文件路径*/
private String path;
/**文件类型*/
private String type;
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
2、controller:
@Autowired
private UploadService uploadService;
/**
* 本地上传
* @param fileBean
* @return
*/
@RequestMapping("/uploadFile")
@ResponseBody
public Result uploadFile(@RequestBody FileBean fileBean){
//不同类型的文件上传到不同给的Bucket
String fileName = fileBean.getFileName();
String path = fileBean.getPath();
String type = fileBean.getType();
switch (type){
case "img":
return uploadService.uploadImg(fileName,path);
case "text":
return uploadService.uploadText(fileName,path);
case "video":
return uploadService.uploadVideo(fileName,path);
case "voice":
return uploadService.uploadVoice(fileName,path);
}
return Result.success();
}
Result是自定义的返回类型,贴一下代码:
package com.dwk.design.result;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
* Description:
* @JsonInclude(Include.NON_NULL) :实体类与json互转的时候属性值为null的不参与序列化
* 即值为null的属性不会返回给前端
* @author: mushi
* @Date: 2021/3/4 9:01
*/
@JsonInclude(Include.NON_NULL)
public class Result<T> {
public static final String SUCCESSFUL_CODE = "200";
public static final String SUCCESSFUL_MESG = "操作成功";
private String code;
private String message;
private String timestamp;
private Integer pageCount;
private Long totalCount;
@JsonInclude(Include.NON_NULL)
private T data;
public Integer getPageCount() {
return this.pageCount;
}
public void setPageCount(Integer pageCount) {
this.pageCount = pageCount;
}
public Long getTotalCount() {
return this.totalCount;
}
public void setTotalCount(Long totalCount) {
this.totalCount = totalCount;
}
public String getCode() {
return this.code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return this.message;
}
public void setMessage(String message) {
this.message = message;
}
public String getTimestamp() {
return this.timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public T getData() {
return this.data;
}
public void setData(T data) {
this.data = data;
}
public Result() {
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
this.timestamp = df.format(LocalDateTime.now());
}
/**枚举异常类型*/
public Result(ErrorType errorType) {
this.code = errorType.getCode();
this.message = errorType.getMessage();
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
this.timestamp = df.format(LocalDateTime.now());
}
public Result(ErrorType errorType, T data) {
this(errorType);
this.data = data;
}
/**状态码、异常信息、*/
private Result(String code, String mesg, T data) {
this.code = code;
this.message = mesg;
this.data = data;
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
this.timestamp = df.format(LocalDateTime.now());
}
public static Result success(Object data) {
return new Result("200", "传输完成", data);
}
public static Result success() {
return success(true);
}
public static Result fail() {
return new Result(ErrorType.SYSTEM_ERROR);
}
public static Result fail(String code, String message) {
return new Result(code, message, "");
}
public static Result fail(ErrorType errorType, Object data) {
return new Result(errorType, data);
}
public static Result fail(OssException exception) {
return new Result(exception.getHttpCode() + "", exception.getErrorMessage(), "");
}
public static Result fail(ErrorType errorType, String message, Object data) {
return new Result(errorType.getCode(), message, data);
}
public static Result fail(ErrorType errorType) {
return fail((ErrorType)errorType, (Object)null);
}
public static Result fail(Object data) {
return new Result(ErrorType.SYSTEM_ERROR, data);
}
@JsonIgnore
public boolean isSuccess() {
return "200".equals(this.code);
}
@JsonIgnore
public boolean isFail() {
return !this.isSuccess();
}
}
3、service:
package com.dwk.design.service;
import com.dwk.design.info.Upload;
import com.dwk.design.config.AliConfig;
import com.dwk.design.result.ErrorType;
import com.dwk.design.result.Result;
import com.dwk.design.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.File;
import java.util.UUID;
/**
* Description:
* 上传文件
* @author: mushi
* @Date: 2021/2/2 9:53
*/
@Service
public class UploadService implements Upload {
/**oss存储空间*/
private static final Integer IMG_BUCKET = 0;
private static final Integer TXT_BUCKET = 1;
private static final Integer VIDEO_BUCKET = 2;
private static final Integer VOICE_BUCKET = 3;
@Autowired
private AliConfig aliConfig;
private FileUtil fileUtil;
private File file;
/**上传图片,上传的文件名=用户文件名+uuid*/
@Override
public Result uploadImg(String fileName, String path){
file = new File(path);
if (!file.exists()){
return Result.fail(ErrorType.FILE_NOT_EXIT);
}
fileName=fileName+"-"+UUID.randomUUID().toString();
this.fileUtil = FileUtil.getFileUtil();
return fileUtil.upLoad(aliConfig,fileName,file,IMG_BUCKET);
}
/**上传文本文件*/
@Override
public Result uploadText(String fileName, String path){
file = new File(path);
if (!file.exists()){
return Result.fail(ErrorType.FILE_NOT_EXIT);
}
fileName=fileName+"-"+UUID.randomUUID().toString();
this.fileUtil = FileUtil.getFileUtil();
return fileUtil.upLoad(aliConfig,fileName,file,TXT_BUCKET);
}
/**上传视频*/
@Override
public Result uploadVideo(String fileName, String path){
file = new File(path);
if (!file.exists()){
return Result.fail(ErrorType.FILE_NOT_EXIT);
}
fileName=fileName+"-"+UUID.randomUUID().toString();
this.fileUtil = FileUtil.getFileUtil();
return fileUtil.upLoad(aliConfig,fileName,file,VIDEO_BUCKET);
}
/**上传音频*/
@Override
public Result uploadVoice(String fileName, String path){
file = new File(path);
if (!file.exists()){
return Result.fail(ErrorType.FILE_NOT_EXIT);
}
fileName=fileName+"-"+UUID.randomUUID().toString();
this.fileUtil = FileUtil.getFileUtil();
return fileUtil.upLoad(aliConfig,fileName,file,VOICE_BUCKET);
}
}
4、文件上传下载工具类:
package com.dwk.design.util;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.dwk.design.config.AliConfig;
import com.dwk.design.result.Result;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Description:
* 上传下载文件工具类
* @author: mushi
* @Date: 2021/2/2 13:30
*/
public class FileUtil {
private static volatile FileUtil fileUtil = null;
private String bucket;
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private List<String> fileNameList;
private FileUtil(){
}
public static FileUtil getFileUtil() {
if (fileUtil == null){
fileUtil = new FileUtil();
}
return fileUtil;
}
/***
* 上传文件
*/
public Result upLoad(AliConfig aliConfig , String fileName , File file , int i){
bucket = aliConfig.getBucketName().get(i);
endpoint = aliConfig.getEndpoint();
accessKeyId = aliConfig.getAccessKeyId();
accessKeySecret = aliConfig.getAccessKeySecret();
fileNameList = new ArrayList<>();
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
if (ossClient.doesBucketExist(bucket)){
//上传文件
ossClient.putObject(bucket,fileName,file);
ObjectListing objectListing = ossClient.listObjects(bucket);
List<OSSObjectSummary> objectSummaries = objectListing.getObjectSummaries();
for (OSSObjectSummary obs:objectSummaries){
fileNameList.add(obs.getKey());
}
if (fileNameList.contains(fileName)){
//文件下载路径,存入数据库和缓存
URL url = ossClient.generatePresignedUrl(bucket, fileName,new Date(System.currentTimeMillis()+3600L * 1000 * 24 * 365 * 1000));
ossClient.shutdown();
return Result.success("下载链接:"+url);
}else{
return Result.fail("1000","上传失败");
}
}else{
System.out.println("创建"+bucket+"Bucket");
ossClient.createBucket(bucket);
this.upLoad(aliConfig,fileName,file,i);
}
return Result.success();
}
/**
* 下载文件
*/
public Result downLoad(){
return Result.success();
}
}