官网API:https://help.aliyun.com/document_detail/32015.html?spm=5176.8466032.bucket-object.1.33ac1450TuX65y
1.获取application.yml中的配置参数
# OSS相关配置信息
aliyun:
oss:
endpoint: # oss对外服务的访问域名
accessKeyId: # 访问身份验证中用到用户标识
accessKeySecret: # 用户用于加密签名字符串和oss用来验证签名字符串的密钥
bucketName: # oss的存储空间
urlPrefix:
policy:
expire: 300 # 签名有效期(S)
maxSize: 10 # 上传文件大小(M)
#callback: # 文件上传成功后的回调地址
@Configuration
@Data
public class AliyunConfig {
@Value("${aliyun.oss.endpoint}")
private String endpoint;
@Value("${aliyun.oss.accessKeyId}")
private String accessKeyId;
@Value("${aliyun.oss.accessKeySecret}")
private String accessKeySecret;
@Value("${aliyun.oss.bucketName}")
private String bucketName;
@Value("${aliyun.oss.urlPrefixe}")
private String urlPrefix;
@Bean
public OSS oSSClient() {
return new OSSClient(endpoint, accessKeyId, accessKeySecret);
}
}
2.上传文件返回结果集
@Data
public class FileUploadResult {
// 文件唯一标识
private String uid;
// 文件名
private String name;
// 状态有:uploading done error removed
private String status;
// 服务端响应内容,如:‘{"status": "success"}‘
private String response;
}
3.错误信息
public enum FileStateEnum {
GET_FILE_FAIL(-1, "获取文件流失败"), GET_FILE_SUCCESS(1, "成功获取文件流ccc"),
NULL_FILE(-1, "上传文件为空"), MAX_SIZE_FILE(-1, "上传图片大小不能超过10M"),
UPLOAD_FILE_FAIL(-1, "上传文件失败"), UPLOAD_FILE_SUCCESS(1, "上传文件成功"),
DELETE_FILE_FAIL(-1, "删除文件失败");
private int state;
private String stateInfo;
FileStateEnum(int state, String stateInfo) {
this.state = state;
this.stateInfo = stateInfo;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public String getStateInfo() {
return stateInfo;
}
public void setStateInfo(String stateInfo) {
this.stateInfo = stateInfo;
}
}
4.controller
/**
* @author 团子
* @desc
* @date 2019-07-31 11:31
*/
@Controller
@RequestMapping({"${adminPath}/cover"})
public class CoverFileUploadController {
@Autowired
private CoverFileUploadService coverFileUploadService;
/**
* @return FileUploadResult
* @author 团子
* @desc 文件上传到oss
* @Param uploadFile
*/
@RequestMapping("file/upload")
@ResponseBody
public FileUploadResult upload(@RequestParam("file") MultipartFile uploadFile)
throws Exception {
return this.coverFileUploadService.upload(uploadFile);
}
/**
* @return FileUploadResult
* @desc 根据文件名删除oss上的文件
* @author 团子
* @Param objectName
*/
@RequestMapping("file/delete")
@ResponseBody
public FileUploadResult delete(@RequestParam("fileName") String objectName)
throws Exception {
return this.coverFileUploadService.delete(objectName);
}
/**
* @return List<OSSObjectSummary>
* @author 团子
* @desc 查询oss上的所有文件
* @Param
*/
@RequestMapping("file/list")
@ResponseBody
public List<OSSObjectSummary> list()
throws Exception {
return this.coverFileUploadService.list();
}
/**
* @return
* @author 团子
* @desc 根据文件名下载oss上的文件
* @Param objectName
*/
@RequestMapping("file/download")
@ResponseBody
public void download(@RequestParam("fileName") String objectName, HttpServletResponse response) throws IOException {
//通知浏览器以附件形式下载
response.setHeader("Content-Disposition",
"attachment;filename=" + new String(objectName.getBytes(), "ISO-8859-1"));
this.coverFileUploadService.exportOssFile(response.getOutputStream(), objectName);
}
}
5.service
@Service
public class CoverFileUploadService {
// 允许上传的格式
private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg",
".jpeg", ".gif", ".png"};
@Autowired
private OSS ossClient;
@Autowired
private AliyunConfig aliyunConfig;
/**
* @author 团子
* @desc 文件上传
* @date 2019-07-31 11:31
*/
public FileUploadResult upload(MultipartFile uploadFile) {
// 校验图片格式
boolean isLegal = false;
for (String type : IMAGE_TYPE) {
if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(),
type)) {
isLegal = true;
break;
}
}
//封装Result对象,并且将文件的byte数组放置到result对象中
FileUploadResult fileUploadResult = new FileUploadResult();
if (!isLegal) {
fileUploadResult.setStatus("error");
return fileUploadResult;
}
//文件新路径
String fileName = uploadFile.getOriginalFilename();
String filePath = getFilePath(fileName);
// 上传到阿里云
try {
ossClient.putObject(aliyunConfig.getBucketName(), filePath, new
ByteArrayInputStream(uploadFile.getBytes()));
} catch (Exception e) {
e.printStackTrace();
//上传失败
fileUploadResult.setStatus("error");
return fileUploadResult;
}
fileUploadResult.setStatus("done");
fileUploadResult.setResponse("success");
fileUploadResult.setName(this.aliyunConfig.getUrlPrefix() + filePath);
fileUploadResult.setUid(String.valueOf(System.currentTimeMillis()));
return fileUploadResult;
}
/**
* @author 团子
* @desc 生成路径以及文件名 例如://images/2019/08/10/15564277465972939.jpg
* @date 2019-07-31 11:31
*/
private String getFilePath(String sourceFileName) {
LocalDate localDate = LocalDate.now();
return "images/" + localDate.getYear()
+ "/" + localDate.getMonth() + "/"
+ localDate.getDayOfMonth() + "/" + System.currentTimeMillis() +
RandomUtils.nextInt(100, 9999) + "." +
StringUtils.substringAfterLast(sourceFileName, ".");
}
/**
* @author 团子
* @desc 查看文件列表
* @date 2019-07-31 11:31
*/
public List<OSSObjectSummary> list() {
// 设置最大个数。
final int maxKeys = 200;
// 列举文件。
ObjectListing objectListing = ossClient.listObjects(new ListObjectsRequest(aliyunConfig.getBucketName()).withMaxKeys(maxKeys));
List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
return sums;
}
/**
* @author 团子
* @desc 删除文件
* @date 2019-07-31 11:31
*/
public FileUploadResult delete(String objectName) {
// 根据BucketName,objectName删除文件
ossClient.deleteObject(aliyunConfig.getBucketName(), objectName);
FileUploadResult fileUploadResult = new FileUploadResult();
fileUploadResult.setName(objectName);
fileUploadResult.setStatus("removed");
fileUploadResult.setResponse("success");
return fileUploadResult;
}
/**
* @author 团子
* @desc 下载文件
* @date 2019-07-31 11:31
*/
public void exportOssFile(OutputStream os, String objectName) throws IOException {
// ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
OSSObject ossObject = ossClient.getObject(aliyunConfig.getBucketName(), objectName);
// 读取文件内容。
BufferedInputStream in = new BufferedInputStream(ossObject.getObjectContent());
BufferedOutputStream out = new BufferedOutputStream(os);
byte[] buffer = new byte[1024];
int lenght = 0;
while ((lenght = in.read(buffer)) != -1) {
out.write(buffer, 0, lenght);
}
if (out != null) {
out.flush();
out.close();
}
if (in != null) {
in.close();
}
}
}