java接入阿里云oss对象存储
导入阿里云的maven环境
<!-- 阿里云SDK-OSS对象存储 -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
编写controller层
package com.fwh.demo.controller.common;
import com.fwh.demo.service.FileService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
@RestController(value = "FileController")
@RequestMapping("/api/file")
public class FileController {
@Autowired
private FileService fileService;
@PostMapping("/upload")
@ApiOperation(value = "图片上传")
public String upload(MultipartFile file) throws IOException {
return fileService.uploadALiYun(file);
}
}
编写接口
package com.fwh.demo.service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
public interface FileService {
/**
* 文件上传到阿里云
*
* @param multipartFile 上传文件
* @return 访问URL
*/
String uploadALiYun(MultipartFile multipartFile) throws IOException;
}
编写实现类
package com.fwh.demo.service;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
@Slf4j
@Service
public class FileServiceImpl implements FileService {
/**
* 文件上传到阿里云
*
* @param multipartFile 上传文件
* @return 访问URL
*/
@Override
public String uploadALiYun(MultipartFile multipartFile) throws IOException {
String endpoint = "";
String accessKey = "";
String secretKey = "";
String bucket = "";
String domain = "";
String dir = "";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKey, secretKey);
// 上传文件流
InputStream inputStream = multipartFile.getInputStream();
//为了使得文件可以重复上传,每次上传的时候需要将文件名进行修改
String fileName = multipartFile.getOriginalFilename();
log.info("图片上传的名字为:{}", fileName);
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
String newFileName = uuid + fileName;
try {
//第一个参数Bucket名称 第二个参数 上传到oss文件路径和文件名称
ossClient.putObject(bucket, dir + newFileName, inputStream);
} catch (Exception e) {
log.info(e.getMessage());
} finally {
// 关闭OSSClient。
ossClient.shutdown();
}
return domain + newFileName;
}
}
到此,已经完成