数据准备
在阿里云申请一个账号,开通对象存储功能,创建一个桶,详细步骤可参考阿里云官方文档
https://help.aliyun.com/product/31815.html?spm=5176.8465980.0.dexternal.c0fa14503jckqF
我已经在对象存储控制台创建了一个桶miaomiao,如下图所示:
本博文重点讲述使用springboot对OSS的访问
创建springboot
我们使用idea快速创建一个springboot项目,引入oss相关依赖。JDK版本为8
pom.xml
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.lagou</groupId>
<artifactId>oss</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>oss</name>
<description>阿里云对象存储</description>
<properties>
<java.version>8</java.version>
</properties>
<dependencies>
<!--springboot 测试支持-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>2.1.8.RELEASE</version>
</dependency>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.8.3</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.9</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
创建配置文件aliyun.properties
aliyun.properties用于存储阿里云的配置文件
aliyun.endpoint=http://oss-cn-beijing.aliyuncs.com
aliyun.accessKeyId=shuaige #请从自己阿里云获取
aliyun.accessKeySecret=meilve #请从自己阿里云获取
aliyun.bucketName=miamiaobucket
aliyun.urlPrefix=http://miamiaobucket.oss-cn-beijing.aliyuncs.com
关键类
项目架构如下图所示
Aliconfig
package com.lagou.oss.config;
import com.aliyun.oss.OSSClient;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
/**
* <p>Title: 阿里云配置类</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2020</p>
* <p>Company: http://www.ubisys.com.cn/</p>
*
* @Auther: cw
* @Date: 2020/9/3 20:34
*/
@Configuration
@PropertySource("classpath:aliyun.properties")
@ConfigurationProperties(prefix = "aliyun")
@Data
public class Aliconfig {
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
private String urlPrefix;
@Bean
public OSSClient oSSClient() {
return new OSSClient(endpoint, accessKeyId, accessKeySecret);
}
}
FileUpLoadService
package com.lagou.oss.service;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.*;
import com.lagou.oss.config.Aliconfig;
import com.lagou.oss.vo.FileUploadResult;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.List;
import java.util.UUID;
/**
* <p>Title: 文件上传服务类</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2020</p>
* <p>Company: http://www.ubisys.com.cn/</p>
*
* @Auther: cw
* @Date: 2020/9/3 20:43
*/
@Service
public class FileUpLoadService {
// 允许上传的格式
private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg",
".jpeg", ".gif", ".png"};
@Autowired
private OSS ossClient;
@Autowired
private Aliconfig aliyunConfig;
/**
* 文件上传
* @param uploadFile
* @return
*/
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");
//this.aliyunConfig.getUrlPrefix() + filePath 文件路径需要保存到数据库
fileUploadResult.setName(this.aliyunConfig.getUrlPrefix() + filePath);
fileUploadResult.setUid(String.valueOf(System.currentTimeMillis()));
return fileUploadResult;
}
/**
* 通过源文件获取 路径和文件名
* @param sourceFileName
* @return
*/
private String getFilePath(String sourceFileName) {
DateTime dateTime = new DateTime();
return "images/" + dateTime.toString("yyyy")
+ "/" + dateTime.toString("MM") + "/"
+ dateTime.toString("dd") + "/" + System.currentTimeMillis() +
RandomUtils.nextInt(100, 9999) + "." +
StringUtils.substringAfterLast(sourceFileName, ".");
}
/**
* 查看文件列表
* @return
*/
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;
}
/**
* @desc 删除文件
*/
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;
}
/**
* 下载文件
* @param os
* @param objectName
* @throws IOException
*/
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();
}
}
}
FileUploadResult
package com.lagou.oss.vo;
import lombok.Data;
/**
* <p>Title: 阿里云oss通用结果返回类 </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2020</p>
* <p>Company: http://www.ubisys.com.cn/</p>
*
* @Auther: cw
* @Date: 2020/9/3 20:41
*/
@Data
public class FileUploadResult {
// 文件唯一标识
private String uid;
// 文件名
private String name;
// 状态有:uploading done error removed
private String status;
// 服务端响应内容,如:'{"status": "success"}'
private String response;
}
FileUploadController
package com.lagou.oss.controller;
import com.aliyun.oss.model.OSSObjectSummary;
import com.lagou.oss.service.FileUpLoadService;
import com.lagou.oss.vo.FileUploadResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
/**
* <p>Title:阿里云oss存储 controller </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2020</p>
* <p>Company: http://www.ubisys.com.cn/</p>
*
* @Auther: cw
* @Date: 2020/9/4 21:31
*/
@Controller
public class FileUploadController {
@Autowired
private FileUpLoadService fileUploadService;
/**
* 文件上传到oss
* @param uploadFile
* @return
* @throws Exception
*/
@RequestMapping("file/upload")
@ResponseBody
public FileUploadResult upload(@RequestParam("file") MultipartFile uploadFile)
throws Exception {
return fileUploadService.upload(uploadFile);
}
/**
* 根据文件名删除
* @param objectName
* @return
* @throws Exception
*/
@RequestMapping("file/delete")
@ResponseBody
public FileUploadResult delete(@RequestParam("fileName") String objectName)
throws Exception {
return fileUploadService.delete(objectName);
}
/**
* 查看桶内所有文件
* @return
* @throws Exception
*/
@RequestMapping("file/list")
@ResponseBody
public List<OSSObjectSummary> list()
throws Exception {
return fileUploadService.list();
}
/**
* 根据文件名进行下载
* @param objectName
* @param response
* @throws IOException
*/
@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"));
fileUploadService.exportOssFile(response.getOutputStream(),objectName);
}
}
测试
文件上传
获取文件列表
文件下载
文件删除
具体的请求,下载源码,在源码的classpath下有postman的请求json
源码地址
https://gitee.com/yulanzhilian.com/lagouphasefourmodulefouthcode/blob/master/README.md