一、在阿里云申请OSS
二、创建SpringBoot项目
1、config
package com.zyl.oss.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import java.io.Serializable;
/**
* @Description: 阿里云 OSS 配置信息
* @Author: zyl
*/
@Data
@Configuration
public class OSSConfig implements Serializable {
private static final long serialVersionUID = -119396871324982279L;
/**
* 阿里云 oss 站点
*/
@Value("${oss.endpoint}")
private String endpoint;
/**
* 阿里云 oss 资源访问 url
*/
@Value("${oss.url}")
private String url;
/**
* 阿里云 oss 公钥
*/
@Value("${oss.accessKeyId}")
private String accessKeyId;
/**
* 阿里云 oss 私钥
*/
@Value("${oss.accessKeySecret}")
private String accessKeySecret;
/**
* 阿里云 oss 文件根目录
*/
@Value("${oss.bucketName}")
private String bucketName;
}
2、controller
package com.zyl.oss.controller;
import com.zyl.oss.config.OSSConfig;
import com.zyl.oss.service.CommonService;
import com.zyl.oss.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
@RestController
@RequestMapping("api/demo/common")
public class CommonController {
@Autowired
private CommonService commonService;
@Autowired
OSSConfig ossConfig;
/**
* 上传文件至阿里云 oss
*/
@RequestMapping(value = "/upload/oss", method = {RequestMethod.POST}, produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseResult uploadOSS(@RequestParam(value = "file") MultipartFile file) throws Exception {
System.out.println(file.getInputStream());
return commonService.uploadOSS(file);
}
@RequestMapping("/delete/oss")
public ResponseResult deleteOss(String objectName) {
System.out.println(objectName + "-------------------------------");
return commonService.delete(objectName);
}
}
}
3、Service
package com.zyl.oss.service;
import com.zyl.oss.utils.ResponseResult;
import org.springframework.web.multipart.MultipartFile;
@SuppressWarnings("all")
public interface CommonService {
/**
* 上传文件至阿里云 oss
*
* @param file
* @param
* @return
* @throws Exception
*/
ResponseResult uploadOSS(MultipartFile file) throws Exception;
ResponseResult delete(String objectName);
}
4、ServiceImpl
package com.zyl.oss.service.impl;
import com.zyl.oss.config.OSSConfig;
import com.zyl.oss.service.CommonService;
import com.zyl.oss.utils.OSSBootUtil;
import com.zyl.oss.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Service("commonService")
@SuppressWarnings("all")
public class CommonServiceImpl implements CommonService {
@Autowired
private OSSConfig ossConfig;
/**
* 上传文件至阿里云 oss
*
* @param file
* @param
* @return
* @throws Exception
*/
@Override
public ResponseResult uploadOSS(MultipartFile file) throws Exception {
// 格式化时间
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String format = simpleDateFormat.format(new Date());
// 高依赖版本 oss 上传工具
String ossFileUrlBoot = null;
/**
* ossConfig 配置类
* file 文件
* "jpc/"+format 上传文件地址 加时间戳
*/
ossFileUrlBoot = OSSBootUtil.upload(ossConfig, file, "jpc/" + format);
System.out.println(ossFileUrlBoot);
Map<String, Object> resultMap = new HashMap<>(16);
// resultMap.put("ossFileUrlSingle", ossFileUrlSingle);
resultMap.put("ossFileUrlBoot", ossFileUrlBoot);
return ResponseResult.ok("上传成功~~", ossFileUrlBoot);
}
@Override
public ResponseResult delete(String objectName) {
ResponseResult delete = OSSBootUtil.delete(objectName, ossConfig);
return delete;
}
}
5、Util
package com.zyl.oss.utils;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.zyl.oss.config.OSSConfig;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.UUID;
@SuppressWarnings("all")
public class OSSBootUtil {
private OSSBootUtil() {
}
/**
* oss 工具客户端
*/
private volatile static OSSClient ossClient = null;
/**
* 上传文件至阿里云 OSS
* 文件上传成功,返回文件完整访问路径
* 文件上传失败,返回 null
*
* @param ossConfig oss 配置信息
* @param file 待上传文件
* @param fileDir 文件保存目录
* @return oss 中的相对文件路径
* @author jiangpengcheng
*/
public static String upload(OSSConfig ossConfig, MultipartFile file, String fileDir) {
initOSS(ossConfig);
StringBuilder fileUrl = new StringBuilder();
try {
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'));
String fileName = System.currentTimeMillis() + "-" + UUID.randomUUID().toString().substring(0, 18) + suffix;
if (!fileDir.endsWith("/")) {
fileDir = fileDir.concat("/");
}
fileUrl = fileUrl.append(fileDir + fileName);
System.out.println(fileUrl + "-----------------");
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentType("image/jpg");
ossClient.putObject(ossConfig.getBucketName(), fileUrl.toString(), file.getInputStream(), objectMetadata);
} catch (IOException e) {
e.printStackTrace();
return null;
}
fileUrl = fileUrl.insert(0, ossConfig.getUrl());
return fileUrl.toString();
}
/**
* 初始化 oss 客户端
*
* @param ossConfig
* @return
*/
public static OSSClient initOSS(OSSConfig ossConfig) {
if (ossClient == null) {
synchronized (OSSBootUtil.class) {
if (ossClient == null) {
ossClient = new OSSClient(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
}
}
}
return ossClient;
}
/**
* 根据前台传过来的文件地址 删除文件
*
* @param objectName
* @param ossConfig
* @return
* @author jiangpengcheng
*/
public static ResponseResult delete(String objectName, OSSConfig ossConfig) {
initOSS(ossConfig);
//将完整路径替换成 文件地址 因为yml里的url有了地址链接https: //oos-all.oss-cn-shenzhen.aliyuncs.com/
// 如果再加上地址 那么又拼接了 所以删除不了 要先把地址替换为 jpc/2020-07-16/1594857669731-51d057b0-9778-4aed.png
String fileName = objectName.replace("https://oos-all.oss-cn-shenzhen.aliyuncs.com/", "");
System.out.println(fileName + "******************************");
// 根据BucketName,objectName删除文件
ossClient.deleteObject(ossConfig.getBucketName(), fileName);
return ResponseResult.ok("删除成功", fileName);
}
}
6、Result
package com.zyl.oss.utils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@NoArgsConstructor
@AllArgsConstructor
@SuppressWarnings("all")
public class ResponseResult implements Serializable {
private Integer code;
private String message;
private Object object;
public static ResponseResult ok(String message) {
return new ResponseResult(200, message, null);
}
public static ResponseResult ok(String message, Object object) {
return new ResponseResult(200, message, object);
}
public static ResponseResult error(String message) {
return new ResponseResult(500, message, null);
}
public static ResponseResult error(String message, Object o) {
return new ResponseResult(500, message, o);
}
}
7、yml
oss:
endpoint: oss-cn-beijing.aliyuncs.com
url: xxxx
accessKeyId: xxxx
accessKeySecret: xxxx
bucketName: xxxx
8、测试上传