对象存储OSS(Object Storage Service)是一款海量、安全、低成本、高可靠的云存储服务,提供99.99%的数据持久性,99.99%的数据可用性。可用于存储任意类型,任意数量,任意大小的非结构化数据。
Spingboot集成亚马逊 AmazonS3的使用
1、引入pom依赖
<!-- aws对象存储 -->
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-s3</artifactId>
<version>1.11.490</version>
</dependency>
2、yml配置
3、初始化AmazonS3
@Component
@Slf4j
public class AwsS3Component implements InitializingBean {
@Value("${aws.accessKey}")
private String accessKey;
@Value("${aws.secretKey}")
private String accessSecret;
@Value("${aws.bucket}")
private String bucket;
@Value("${aws.endpoint}")
private String endpoint;
private AmazonS3 client;
@Override
public void afterPropertiesSet() {
ClientConfiguration config = new ClientConfiguration();
config.setProtocol(Protocol.HTTP);
config.disableSocketProxy();
this.client = AmazonS3ClientBuilder
.standard()
.withClientConfiguration(config)
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey, accessSecret)))
.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(endpoint, Regions.CN_NORTH_1.getName()))
.enablePathStyleAccess()
.build();
}
/**
* 执行文件上传
*
* @param file 要上传的文件的路径
* @param key 存储文件的路径
* @return 文件路径
*/
public String upload(File file, String key) {
client.putObject(new PutObjectRequest(bucket, key, file).withCannedAcl(CannedAccessControlList.PublicRead));
GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(bucket, key);
URL url = client.generatePresignedUrl(urlRequest);
return url.toString();
}
/**
* 文件流执行文件上传
* @param input
* @param key
* @return
* @throws IOException
*/
public String upload(InputStream input, String key) throws IOException {
Date expireDate = new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(30));
ObjectMetadata metadata = new ObjectMetadata();
metadata.setHttpExpiresDate(expireDate);
metadata.setContentLength(input.available());
client.putObject(new PutObjectRequest(bucket, key, input, metadata).withCannedAcl(CannedAccessControlList.PublicRead));
GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(bucket, key);
URL url = client.generatePresignedUrl(urlRequest);
return url.toString();
}
4、文件上传实现类
@SneakyThrows
@Override
public ResultDTO awsUpload(MultipartFile file) {
//空文件限制
if(file.isEmpty()){
return ResultDTO.response("上传文件不能为空!");
}
//文件大小限制,最大单文件20M
if(file.getSize() > fileSize){
return ResultDTO.response("上传文件大小超过50M!");
}
//获取文件md5值
String fileMd5 = fileMd5Util.getFileMd5Value(file);
String fileName = file.getOriginalFilename();
String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
StringBuffer tempFileName = new StringBuffer(fileMd5);
tempFileName.append(".").append(prefix);
String localFileName = tempFileName.toString();
String upload = awsS3Component.upload(file.getInputStream(), localFileName);
log.info("文件---[{}]---上传到S3服务器成功!",localFileName);
//文件访问路径
String url = endpoint + "/"+ bucket + "/" + localFileName;
return ResultDTO.requestSuccess(url);
}
5、控制器Controller
@PostMapping(value = "/uploadObjectOSS",produces = {MediaType.APPLICATION_JSON_UTF8_VALUE},consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResultDTO uploadObjectOSS(@ApiParam("文件") @RequestPart("file") MultipartFile file) @RequestParam("type") Integer type) throws IOException {
return ossService.awsUpload(file);
}
6、获取文件md5值工具类
@Slf4j
@Component
public class FileMd5Util {
/**
* 文件md5值
* @param multipartFile
* @return
*/
public String getFileMd5Value(MultipartFile multipartFile) {
InputStream in = null;
try {
in = multipartFile.getInputStream();
byte[] buffer = new byte[2048];
MessageDigest digest = MessageDigest.getInstance("MD5");
while (true) {
int len = in.read(buffer, 0, 2048);
if (len != -1) {
digest.update(buffer, 0, len);
} else {
break;
}
}
in.close();
byte[] md5Bytes = digest.digest();
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++) {
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16) {
hexValue.append("0");
}
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
} catch (Exception e) {
log.error("获取文件md5失败");
} finally {
try {
in.close();
} catch (IOException ex) {
log.error("关闭流异常", ex);
}
}
return null;
}
}
s3browser客户端快捷方便管理上传之后的文件和文件目录存储结构
1、进入下载页面进行下载
https://s3browser.com/