1.登录阿里云官网获取四样东西
阿里云官网:https://oss.console.aliyun.com/
//不明白具体怎么操作的百度
endpoint
accessKeyId
accessKeySecret
bucket
2.代码实现
2.1 导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- swagger ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.8.3</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10.1</version>
</dependency>
<!-- apache-common-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2.2 配置swagger
方便我们待会进行测试
package com.cz.config;
import com.google.common.base.Predicates;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
**
*@Date :2021/8/23 15:05
*@Description: swagger配置类
*/
@Configuration
@EnableSwagger2// 开启swagger2
public class Swagger2Config {
@Bean
public Docket webApiConfig() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("webApi")
.apiInfo(webApiInfo())
.select()
.paths(Predicates.not(PathSelectors.regex("/error.*")))
.build();
}
private ApiInfo webApiInfo() {
return new ApiInfoBuilder()
.title("SpringBoot整合OSS-API文档")
.description("阿里云OSS-文件上传下载测试")
.version("1.0")
.contact(new Contact("CSP", "https://blog.csdn.net/weixin_44130574?spm=1001.2101.3001.5343", ""))
.build();
}
}
2.3 配置Oss服务
这里为了方便我们的学习,我就直接写在了service类了,在实际开发中,一般都是编写在配置文件当中
package com.cz.service;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.cz.enums.EmunsCode;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
@Service
public class FileUploadService {
public static final String endpoint = "oss-xxxxxxxcs.com";
public static final String accessKeyId = "LTAxxxxxxx63P77E";
public static final String accessKeySecret = "Cftxxxxxxxxx36v7QWB";
public static final String bucketName = "xxxx6";
public static OSS generateOssClient(){
return new OSSClient(endpoint,accessKeyId,accessKeySecret);
}
public String upload(MultipartFile multipartFile){
String fileName = multipartFile.getOriginalFilename();
String fileType = fileName.substring(fileName.lastIndexOf("."));
//给文件随机生成一个唯一的新名字
String newFileName = UUID.randomUUID().toString() + fileType;
//文件保存的目录
String fileDir = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
//oss上面的存储路径
String ossPath=fileDir+"/"+newFileName;
InputStream inputStream=null;
try {
inputStream= multipartFile.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
/**
* 下面两行代码是重点坑:
* 现在阿里云OSS 默认图片上传ContentType是image/jpeg
* 也就是说,获取图片链接后,图片是下载链接,而并非在线浏览链接,
* 因此,这里在上传的时候要解决ContentType的问题,将其改为image/jpg
*/
ObjectMetadata meta = new ObjectMetadata();
meta.setContentType("image/jpg");
OSS ossClient = generateOssClient();
ossClient.putObject(bucketName,ossPath,inputStream,meta);
// 文件保存地址 这个在实际业务中应该存到数据库
String returnURl="http://"+bucketName+"."+endpoint+"/"+ossPath;
return "上传成功";
}
public String downLoad(String fileName, HttpServletResponse response) throws UnsupportedEncodingException {
// 文件名以附件的形式下载
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
//在实际开发中 这里的路径应该是从数据库查询出来的
String fileType = fileName.substring(fileName.lastIndexOf("."));
String fileDir = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
String ossPath=fileDir+"/"+fileName;
OSS oss = generateOssClient();
OSSObject ossObject = oss.getObject(bucketName, ossPath);
//获取文件流
InputStream in = ossObject.getObjectContent();
BufferedInputStream bufferedInputStream = new BufferedInputStream(in);
ServletOutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
BufferedOutputStream out = new BufferedOutputStream(outputStream);
//定义一个缓冲数组
byte[] bytes = new byte[1024];
int len=0;
//从输入流读取字节 放在缓存数组 赋值给len 依次循环
while ((len=in.read(bytes))!=-1){
out.write(bytes,0,len);
}
if (out != null) {
out.flush();
out.close();
}
if (in != null) {
in.close();
}
return EmunsCode.SUCCESS.getMsg();
} catch (IOException e) {
e.printStackTrace();
return EmunsCode.ERROR.getMsg();
}
}
/*public String deleteFile(String fileName){
// 删除也是同样的道理 赶紧去试试吧
ossClient.deleteObject(bucketName, fileKey);
}
*/
}
controlelr
package com.cz.controller;
import com.cz.service.FileUploadService;
import com.sun.org.apache.regexp.internal.RE;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
/**
* *
*
* @Date 2021/8/23 16:20
* @Description
* @Param
*/
@RestController
@Api("Oss服务模块")
public class OssController {
@Autowired
FileUploadService fileUploadService;
@ApiOperation("文件上传")
@RequestMapping(value = "/upload",method = RequestMethod.POST)
public String uploadFile(MultipartFile multipartFile){
String upload = fileUploadService.upload(multipartFile);
return upload ;
}
@ApiOperation("文件下载")
@RequestMapping(value = "/download",method = RequestMethod.POST)
public String downLoad(@RequestParam("fileName") String fileName, HttpServletResponse response){
String result = null;
try {
result = fileUploadService.downLoad(fileName,response);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result ;
}
}
定义结果集状态枚举类
package com.cz.enums;
/**
* *
*
* @Date 2021/8/23 15:28
* @Description
* @Param
*/
public enum EmunsCode {
SUCCESS("success",200),ERROR("error",500);
private String msg;
private Integer code;
EmunsCode(String msg, Integer code) {
this.msg = msg;
this.code = code;
}
EmunsCode(String msg) {
this.msg = msg;
}
EmunsCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
2.4 访问swagger进行测试
登录自己的阿里云查看文件是否上传成功