准备
-
登录阿里云平台:https://www.aliyun.com/
-
产品分类中选择对象存储OSS
-
如果没开通,点击立即开通,如果开通了,点击管理控制台
-
进入管理平台后,创建Bucket
-
创建新目录,datas
SpringBoot操作
- 新建工程,pom.xml
<!--spring boot的支持-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.1.RELEASE</version>
</parent>
<dependencies>
<!--springboot 测试支持-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.8.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.10</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
- application.properties
server.port=8999
- aliyun.properties
aliyun.endpoint=http://oss-cn-beijing.aliyuncs.com
aliyun.accessKeyId=自己的accessKeyId
aliyun.accessKeySecret=自己的accessKeySecret
aliyun.bucketName=abc-oss
aliyun.urlPrefix=https://abc-oss.oss-cn-beijing.aliyuncs.com/
- 编写配置类
package com.lx.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;
@Configuration
@PropertySource("classpath:aliyun.properties")
@ConfigurationProperties(prefix = "aliyun")
@Data
public class AliyunConfig {
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);
}
}
- 编写实体类
package com.lx.pojo;
import lombok.Data;
@Data
public class UpLoadResult {
// 文件唯一标识
private String uid;
// 文件名
private String name;
// 状态有:uploading done error removed
private String status;
// 服务端响应内容,如:'{"status": "success"}'
private String response;
}
package com.lx.pojo;
import lombok.Data;
@Data
public class Result {
private Integer code;
private String message;
}
- 编写service及实现类
package com.lx.service;
import com.lx.pojo.Result;
import com.lx.pojo.UpLoadResult;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
public interface IFileUpLoadService {
UpLoadResult upload(MultipartFile uploadFile);
Result download(String uid, HttpServletResponse response);
Result delete(String uid);
}
package com.lx.service.impl;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.OSSObject;
import com.lx.config.AliyunConfig;
import com.lx.pojo.Result;
import com.lx.pojo.UpLoadResult;
import com.lx.service.IFileUpLoadService;
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 javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.UUID;
@Service
public class FileUpLoadServiceImpl implements IFileUpLoadService {
@Autowired
private AliyunConfig aliyunConfig;
@Autowired
private OSSClient ossClient;
// 限制上传文件大小
private static final Long MAX_SIZE = 1024L * 1024 * 5;
// 允许上传的格式
private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg", ".jpeg", ".gif", ".png"};
public UpLoadResult upload(MultipartFile uploadFile) {
// 校验图片格式
boolean isLegal = false;
for (String type : IMAGE_TYPE) {
if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(), type)) {
isLegal = true;
break;
}
}
UpLoadResult uploadResult = new UpLoadResult();
if(MAX_SIZE < uploadFile.getSize()) {
uploadResult.setStatus("文件大小不能超过5m");
return uploadResult;
}
if (!isLegal) {
uploadResult.setStatus("error");
return uploadResult;
}
String fileName = uploadFile.getOriginalFilename();
String filePath = getFilePath(fileName);
try {
ossClient.putObject(aliyunConfig.getBucketName(), filePath, new ByteArrayInputStream(uploadFile.getBytes()));
} catch (IOException e) {
e.printStackTrace();
//上传失败
uploadResult.setStatus("error");
return uploadResult;
}
uploadResult.setStatus("done");
uploadResult.setName(this.aliyunConfig.getUrlPrefix() + filePath);
uploadResult.setUid(String.valueOf(System.currentTimeMillis()));
return uploadResult;
}
private String getFilePath(String sourceFileName) {
DateTime dateTime = new DateTime();
return "datas/" + dateTime.toString("yyyy")
+ "/" + dateTime.toString("MM") + "/"
+ dateTime.toString("dd") + "/" + UUID.randomUUID().toString() +
"." + StringUtils.substringAfterLast(sourceFileName, ".");
}
@Override
public Result download(String uid, HttpServletResponse response) {
Result result = new Result();
try {
String bucketName = aliyunConfig.getBucketName();
OSSObject ossObject = ossClient.getObject(bucketName, uid);
int buffer = 1024 * 10;
byte data[] = new byte[buffer];
if (ossObject != null) {
InputStream inputStream = ossObject.getObjectContent();
// 文件名可以任意指定
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(uid, "UTF-8"));
int read;
while ((read = inputStream.read(data)) != -1) {
response.getOutputStream().write(data, 0, read);
}
response.getOutputStream().flush();
response.getOutputStream().close();
ossObject.close();
}
result.setCode(404);
result.setMessage("文件不存在");
return result;
} catch (Exception e) {
OSSException ee = (OSSException) e;
e.printStackTrace();
result.setCode(500);
result.setMessage(e.getMessage());
return result;
}
}
@Override
public Result delete(String uid) {
Result result = new Result();
try {
String bucketName = aliyunConfig.getBucketName();
ossClient.deleteObject(bucketName, uid);
result.setCode(200);
result.setMessage("success");
} catch (Exception e) {
e.printStackTrace();
result.setCode(500);
result.setMessage("fail");
}
return result;
}
}
- 编写controller
package com.lx.controller;
import com.lx.pojo.Result;
import com.lx.pojo.UpLoadResult;
import com.lx.service.IFileUpLoadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
@Controller
@RequestMapping("/oss")
public class UpLoadController {
@Autowired
private IFileUpLoadService fileUpLoadService;
@PostMapping("/upload")
@ResponseBody
public UpLoadResult upload(@RequestParam("file") MultipartFile multipartFile) {
return this.fileUpLoadService.upload(multipartFile);
}
@GetMapping("/download")
@ResponseBody
public Result download(@RequestParam("uid") String uid, HttpServletResponse response){
return fileUpLoadService.download(uid,response);
}
@DeleteMapping("/delete")
@ResponseBody
public Result delete(@RequestParam("uid") String fileName){
return fileUpLoadService.delete(fileName);
}
}
- 编写启动类
package com.lx;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class OSSApplication {
public static void main(String[] args) {
SpringApplication.run(OSSApplication.class, args);
}
}
- 用postman测试上传、下载、删除