淄博哪家公司做网站最好,怎么创建卡密网站,专业制作网站系统,html书店网站建设springboot整合oss实现文件的上传,查看,删除,下载
1.什么是对象存储 OSS?
答#xff1a;阿里云对象存储服务#xff08;Object Storage Service#xff0c;简称 OSS#xff09;#xff0c;是阿里云提供的海量、安全、低成本、高可靠的云存储服务。其数据设计持久性不低…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
dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-test/artifactIdscopetest/scope/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-devtools/artifactIdoptionaltrue/optional/dependencydependencygroupIdcom.aliyun.oss/groupIdartifactIdaliyun-sdk-oss/artifactIdversion2.8.3/version/dependencydependencygroupIdorg.projectlombok/groupIdartifactIdlombok/artifactIdversion1.18.4/versionscopeprovided/scope/dependencydependencygroupIdjoda-time/groupIdartifactIdjoda-time/artifactIdversion2.9.9/version/dependencydependencygroupIdorg.apache.commons/groupIdartifactIdcommons-lang3/artifactIdversion3.8.1/version/dependencyapplication.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 ListOSSObjectSummary* Param*/RequestMapping(file/list)ResponseBodypublic ListOSSObjectSummary 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 ListOSSObjectSummary list() {// 设置最大个数。final int maxKeys 200;// 列举文件。ObjectListing objectListing ossClient.listObjects(new ListObjectsRequest(aliyunConfig.getBucketName()).withMaxKeys(maxKeys));ListOSSObjectSummary 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里面 也已经删除了