springboot整合oss实现文件的上传,查看,删除,下载
1.什么是对象存储 OSS?
答:阿里云对象存储服务(Object Storage Service,简称 OSS),是阿里云提供的海量、安全、低成本、高可靠的云存储服务。其数据设计持久性不低于 99.9999999999%(12 个 9),服务设计可用性(或业务连续性)不低于 99.995%。
OSS 具有与平台无关的 RESTful API 接口,您可以在任何应用、任何时间、任何地点存储和访问任意类型的数据。
您可以使用阿里云提供的 API、SDK 接口或者 OSS 迁移工具轻松地将海量数据移入或移出阿里云 OSS。数据存储到阿里云 OSS 以后,您可以选择标准存储(Standard)作为移动应用、大型网站、图片分享或热点音视频的主要存储方式,也可以选择成本更低、存储期限更长的低频访问存储(Infrequent Access)和归档存储(Archive)作为不经常访问数据的存储方式。
有关oss更多,更详细的介绍请参考阿里云oss对象储存官方文档地址
2.登录阿里云,进入到控制台
3.创建Bucket
点击确定,这样我们就建好了。
下面我们来开始写代码?
新建一个spring boot项目
导入如下依赖
pom.xml
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><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-devtools</artifactId><optional>true</optional></dependency><dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss</artifactId><version>2.8.3</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.4</version><scope>provided</scope></dependency><dependency><groupId>joda-time</groupId><artifactId>joda-time</artifactId><version>2.9.9</version></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.8.1</version></dependency>
application.properties配置文件
accessKeyId、accessKeySecret需要在accesskeys里面查看
编写一个配置文件AliyunConfig.class
package com.tuanzi.config;import com.aliyun.oss.OSS;
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;
/*** @desc*/
@Configuration
@PropertySource(value = {"classpath:application.properties"})
@ConfigurationProperties(prefix = "aliyun")
@Data
public class AliyunConfig {private String endpoint;private String accessKeyId;private String accessKeySecret;private String bucketName;private String urlPrefix;@Beanpublic OSS oSSClient() {return new OSSClient(endpoint, accessKeyId, accessKeySecret);}
}
controller类
package com.tuanzi.controller;import com.tuanzi.service.FileUploadService;
import com.tuanzi.vo.FileUploadResult;
import com.aliyun.oss.model.OSSObjectSummary;
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;/*** @desc*/
@Controller
public class FileUploadController {@Autowiredprivate FileUploadService fileUploadService;/*** @desc 文件上传到oss* @return FileUploadResult* @Param uploadFile*/@RequestMapping("file/upload")@ResponseBodypublic FileUploadResult upload(@RequestParam("file") MultipartFile uploadFile)throws Exception {return this.fileUploadService.upload(uploadFile);}/*** @return FileUploadResult* @desc 根据文件名删除oss上的文件* @Param objectName*/@RequestMapping("file/delete")@ResponseBodypublic FileUploadResult delete(@RequestParam("fileName") String objectName)throws Exception {return this.fileUploadService.delete(objectName);}/*** @desc 查询oss上的所有文件* @return List<OSSObjectSummary>* @Param*/@RequestMapping("file/list")@ResponseBodypublic List<OSSObjectSummary> list()throws Exception {return this.fileUploadService.list();}/*** @desc 根据文件名下载oss上的文件* @return* @Param objectName*/@RequestMapping("file/download")@ResponseBodypublic void download(@RequestParam("fileName") String objectName, HttpServletResponse response) throws IOException {//通知浏览器以附件形式下载response.setHeader("Content-Disposition","attachment;filename=" + new String(objectName.getBytes(), "ISO-8859-1"));this.fileUploadService.exportOssFile(response.getOutputStream(),objectName);}
}
service
package com.tuanzi.service;import com.tuanzi.config.AliyunConfig;
import com.tuanzi.vo.FileUploadResult;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.*;
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;/*** @desc*/
@Service
public class FileUploadService {// 允许上传的格式private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg",".jpeg", ".gif", ".png"};@Autowiredprivate OSS ossClient;@Autowiredprivate AliyunConfig aliyunConfig;/*** @desc 文件上传*/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, newByteArrayInputStream(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;}/*** @desc 生成路径以及文件名 例如://images/2019/08/10/15564277465972939.jpg*/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, ".");}/*** @desc 查看文件列表*/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;}/*** @desc 下载文件*/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();}}
}
返回值类
package com.tuanzi.vo;import lombok.Data;/*** @desc 返回值*/
@Data
public class FileUploadResult {// 文件唯一标识private String uid;// 文件名private String name;// 状态有:uploading done error removedprivate String status;// 服务端响应内容,如:'{"status": "success"}'private String response;
}
这样就完成了
我们来运行一下项目
看看效果:访问http://localhost:8080/upload.html
我们来上传一个不符合格式的图片,会有提示信息
来上传一个符合的
上传成功后会直接显示出来。我们来看看oss里面是否有我们上传的图片
发现也有
接下来我们来测试一下查询,下载,和删除
访问:http://localhost:8080/manager.html
会看到我们上传的图片
这里简单的写了个例子
下载图片
删除图片
来看看oss里面
也已经删除了!!!