第一步maven依赖
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>liurui</artifactId>
<groupId>com.liurui</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>service-oss</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>com.liurui</groupId>
<artifactId>service-base</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--lombok用来简化实体类:需要安装lombok插件-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!--aliyunOSS-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
</dependency>
<!-- 日期工具栏依赖 -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
<!--让自定义的配置在application.yaml进行自动提示-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
</project>
第二步思考 service层接口的设计
观察测试用例
public class Demo {
public static void main(String[] args) throws Exception {
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// 填写Bucket名称,例如examplebucket。
String bucketName = "examplebucket";
// 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
String objectName = "exampledir/exampleobject.txt";
// 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。
// 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。
String filePath= "D:\\localpath\\examplefile.txt";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
InputStream inputStream = new FileInputStream(filePath);
// 创建PutObjectRequest对象。
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
// 设置该属性可以返回response。如果不设置,则返回的response为空。
putObjectRequest.setProcess("true");
// 创建PutObject请求。
PutObjectResult result = ossClient.putObject(putObjectRequest);
// 如果上传成功,则返回200。
System.out.println(result.getResponse().getStatusCode());
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
我们可以把下面的处理成为,从yml的读取,他们是经常改变的
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// 填写Bucket名称,例如examplebucket。
String bucketName = "examplebucket";
创建 putObjectRequest 远程客户端对象,需要的参数 (上传到哪一个虚拟内存中,把文件上传到该内存的哪一个文件夹下 , 文件流);
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
我们需要 后两个参数 objectName, inputStream 这个是由前台传递过来的bucketName是由后台决定的,所以我们就将 前台传递过来的两个作为一个参数。
由于我们要保证文件保证文件的唯一性,所以得充型修改文件的名字,组成独一无二的文件,所以多了一个,fileName的参数
接口定义如下
package com.xiaoliu.system.oss.service;
import java.io.InputStream;
/**
* @description:
* @author: 刘瑞_LiuRui
* @data: 2023/01/04
* @Version 1.0
**/
/**
* module
*/
public interface FileService {
String upload(InputStream inputStream, String module,String fileName);
}
实现类 FileServiceImpl
package com.xiaoliu.system.oss.service.impl;
import cn.hutool.core.date.DateTime;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.xiaoliu.system.oss.service.FileService;
import com.xiaoliu.system.oss.util.OssProperties;
import org.springframework.stereotype.Service;
import java.io.InputStream;
import java.util.UUID;
/**
* @description:
* @author: 刘瑞_LiuRui
* @data: 2023/01/04
* @Version 1.0
**/
@Service
public class FileServiceImpl implements FileService {
@Override
public String upload(InputStream inputStream, String module, String fileName) {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(
OssProperties.ENDPOINT,
OssProperties.KEY_ID,
OssProperties.KEY_SECRET);
//判断oss实例是否存在:如果不存在则创建,如果存在则获取
if(!ossClient.doesBucketExist(OssProperties.BUCKET_NAME)){
//创建bucket
ossClient.createBucket(OssProperties.BUCKET_NAME);
//设置oss实例的访问权限:公共读
ossClient.setBucketAcl(OssProperties.BUCKET_NAME, CannedAccessControlList.PublicRead);
}
//构建日期路径:avatar/2019/02/26/文件名
String folder = new DateTime().toString("yyyy/MM/dd");
//文件名:uuid.扩展名
fileName = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
//文件根路径
String key = module + "/" + folder + "/" + fileName;
//文件上传至阿里云
ossClient.putObject(OssProperties.BUCKET_NAME, key, inputStream);
// 关闭OSSClient。
ossClient.shutdown();
//阿里云文件绝对路径
return "https://" + OssProperties.BUCKET_NAME + "." + OssProperties.ENDPOINT + "/" + key;
}
}
FileController
package com.xiaoliu.system.oss.controller.api;
import com.xiaoliu.system.common.exception.BusinessException;
import com.xiaoliu.system.common.result.R;
import com.xiaoliu.system.common.result.ResponseEnum;
import com.xiaoliu.system.oss.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
/**
* @description:
* @author: 刘瑞_LiuRui
* @data: 2023/01/04
* @Version 1.0
**/
@CrossOrigin //跨域
@RestController
@RequestMapping("/api/oss/file")
public class FileController {
@Resource
private FileService fileService;
/**
* 文件上传
*/
@PostMapping("/upload")
public String upload(
@RequestParam("file") MultipartFile file,
@RequestParam("module") String module) {
try {
InputStream inputStream = file.getInputStream();
String originalFilename = file.getOriginalFilename();
String uploadUrl = fileService.upload(inputStream, module, originalFilename);
//返回r对象
return uploadUrl;
} catch (IOException e) {
throw new BusinessException(ResponseEnum.UPLOAD_ERROR, e);
}
}
}
使用postmen进行测试接口
文件删除
1、业务层
Service接口:FileService.java
/**
* 根据路径删除文件
* @param url
*/
void removeFile(String url);
实现:FileServiceImpl.java
/**
* 根据路径删除文件
* @param url
*/
@Override
public void removeFile(String url) {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(
OssProperties.ENDPOINT,
OssProperties.KEY_ID,
OssProperties.KEY_SECRET);
/**
* https://xialiu-system-file.oss-cn-hangzhou.aliyuncs.com/aaa/2023/01/04/3cf68a19-4f89-4f92-b242-66c0402f1788.sql?Expires=1672888777&OSSAccessKeyId=TMP.3KfwkbSKvTKVbCp2ND1iU9QxCNR9yEK9NTLbds8FzK9zD2dP3gu6AFX957kU4hyTwJip4hBxLfEGwpnAgYihoB3G7fARZV&Signature=VsW9Rd3I9Xwm%2F1%2BRL9E8PD0CGa0%3D
**/
//文件名(服务器上的文件路径)
String host = "https://" + OssProperties.BUCKET_NAME + "." + OssProperties.ENDPOINT + "/";
String objectName = url.substring(host.length());
// 发现截取后url地址不对,将?后面的舍弃才可以
// file/2023/01/05/7b0b5c97-c417-45bc-8635-98d8fd382513.xlsx?Expires=1672911553&OSSAccessKeyId=TMP.3KfwkbSKvTKVbCp2ND1iU9QxCNR9yEK9NTLbds8FzK9zD2dP3gu6AFX957kU4hyTwJip4hBxLfEGwpnAgYihoB3G7fARZV&Signature=Q%2FHjChRgkAkClcCO9IZWdDtmY5E%3D
objectName = objectName.split("\\?")[0];
// 删除文件。
ossClient.deleteObject(OssProperties.BUCKET_NAME, objectName);
// 关闭OSSClient。
ossClient.shutdown();
}
2、控制层
@ApiOperation("删除OSS文件")
@DeleteMapping("/remove")
public R remove(
@ApiParam(value = "要删除的文件路径", required = true)
@RequestParam("url") String url) {
fileService.removeFile(url);
return R.ok().message("删除成功");
}