一、开始前准备工作
购买并注册阿里云对象存储服务器(价格不算贵)
查看官方文档,练习基本的api
二、展示自己项目中使用
1.pom.xml文件
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
2.MaterialService :图片上传下载代码实现(提取文件时候加了redis,不需要的可以删除不用)
@Component
public class MaterialService {
private static final String POINT_CHAR = ".";
@Resource
private RedisCache redisCache;
@Resource
private MaterialDao materialDao;
/**
* 文件上传
*
* @param multipartFile 文件实体
* @param moduleName 所属模块:作为文件前缀
* @param userDto 当前用户信息
*/
public String uploadFile(MultipartFile multipartFile, String moduleName) {
try {
String fileName = multipartFile.getOriginalFilename();
if (StringUtils.isEmpty(fileName)) {
fileName = "未命名";
}
return uploadFile(fileName, multipartFile.getSize(), moduleName, multipartFile.getInputStream());
} catch (IOException e) {
return null;
}
}
/**
* 上传文件至服务器(存取成功会生成uuid,用于之后取图片地址使用)
*
* @param fileName 文件名 如:background.png
* @param inputStream 文件输入流
*/
public String uploadFile(String fileName, Long fileSize, String moduleName, InputStream inputStream, UserDto userDto) {
String ext = "";
String uuid = UUID.randomUUID().toString();
if (fileName.contains(POINT_CHAR)) {
ext = fileName.substring(fileName.lastIndexOf(".") + 1);
}
try {
String serverPath = String.format("%s/%s.%s", moduleName, uuid, ext);
AliOssHelper.upload(serverPath, inputStream);
} catch (Exception e) {
Loggers.error("文件上传失败=>" + e.getMessage());
uuid = null;
}
return uuid;
}
/**
* 通过uuid 获取临时url文件查询地址(这里获取地址有效时间八小时)
*
* @param uuid id
* @return URL
*/
public URL getSavePath(String uuid) {
URL url = AliOssHelper.accessUrl(materialEntity.getServerPath(), 60 * 60 * 8L);
return url ;
}
}
3.controller
@RestController
@Api(tags = "文件操作")
@RequestMapping("/file")
public class FileController {
@Resource
private MaterialService materialService;
@GetMapping("/preview/url")
@ApiOperation(value = "获取文件临时访问地址", notes = "获取文件临时访问地址")
public Result getFileTempAccessUrl(@ApiParam(name = "guid", value = "文件guid")
@RequestParam String guid) {
return Result.success(materialService.getSavePath(guid));
}
@PostMapping("/upload")
@ApiOperation(value = "上传文件", notes = "上传文件")
public Result uploadBidFile(@ApiParam(name = "file", value = "文件实体")
@RequestParam MultipartFile file,
@ApiParam(name = "module", value = "模块名", required = false)
@RequestParam(required = false) String module) throws Exception {
if (file == null || file.isEmpty()) {
return Result.error(ResultCode.PARAMS_ERROR);
}
String fileGuid = materialService.uploadFile(file, module);
URL previewPath = materialService.getSavePath(fileGuid);
Map<String, Object> result = BeanUtils.bean2map(materialEntity);
result.put("previewPath", previewPath);
return Result.success(result);
}
}
4.阿里云api方法,个人账户信息配置
import lombok.Data;
@Data
public class OssProperties {
private String endPoint;
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
public OssProperties() {
this.endPoint = "http://oss-cn-shanghai.aliyuncs.com";
this.accessKeyId = "XXXX输入自己的keyIdXXXX";
this.accessKeySecret = "XXXX输入自己的keySecretXXXX";
this.bucketName = "XXX自己建的文件夹名称XXX"; }
public OssProperties(String endPoint, String accessKeyId, String accessKeySecret, String bucketName) {
this.endPoint = endPoint;
this.accessKeyId = accessKeyId;
this.accessKeySecret = accessKeySecret;
this.bucketName = bucketName;
}
}
api方法(MaterialService 中调用)
public class AliOssHelper {
public static void main(String[] args) throws Exception {
//upload("test/bpmprocess.bpmn", new FileInputStream("F://testprocess.bpmn"));
System.out.println(fileExist("test/5dcb9ad1-d0cd-4899-aac1-cda24e354cc8.bpmn"));
}
private static OSS getClient(OssProperties properties) {
return new OSSClientBuilder().build(properties.getEndPoint(), properties.getAccessKeyId(), properties.getAccessKeySecret());
}
/**
* 上传文件至服务器
*
* @param serverPath 文件服务器全路径名
* @param is 输入流传入
*/
public static void upload(OssProperties properties, String serverPath, InputStream is) {
OSS client = getClient(properties);
client.putObject(properties.getBucketName(), serverPath, is);
client.shutdown();
}
public static void upload(String serverPath, InputStream is) {
upload(new OssProperties(), serverPath, is);
}
/**
* 下载文件
*
* @param serverPath 文件服务器全路径名
* @param os 输出流接收
*/
public static void download(OssProperties properties, String serverPath, OutputStream os) {
OSS client = getClient(properties);
OSSObject ossObject = client.getObject(properties.getBucketName(), serverPath);
try {
byte[] bytes = IOUtils.readStreamAsByteArray(ossObject.getObjectContent());
os.write(bytes);
os.close();
} catch (IOException e) {
Loggers.error("下载文件错误=>" + e.getMessage());
e.printStackTrace();
}
client.shutdown();
}
public static void download(String serverPath, OutputStream os) {
download(new OssProperties(), serverPath, os);
}
/**
* 判断文件是否存在服务器
*
* @param serverPath 文件服务器全路径名
*/
public static Boolean fileExist(OssProperties properties, String serverPath) {
OSS client = getClient(properties);
boolean res = client.doesObjectExist(properties.getBucketName(), serverPath);
client.shutdown();
return res;
}
public static Boolean fileExist(String serverPath) {
return fileExist(new OssProperties(), serverPath);
}
/**
* 获取可临时访问的路径
*
* @param serverPath 服务器相对路径
* @param expire 有效期(秒)
*/
public static URL accessUrl(OssProperties properties, String serverPath, Long expire) {
OSS client = getClient(properties);
Date expireTime = new Date(System.currentTimeMillis() + expire * 1000);
URL url = client.generatePresignedUrl(properties.getBucketName(), serverPath, expireTime);
client.shutdown();
return url;
}
public static URL accessUrl(String serverPath, Long expire) {
return accessUrl(new OssProperties(), serverPath, expire);
}
}
三、测试