aws s3 图片批量上传
方法
1.引入依赖
<!-- AWS S3 -->
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-s3</artifactId>
<version>1.12.62</version>
</dependency>
2.文件上传和下载
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.UUID;
public class S3Utils {
/**
* access_key_id 访问密钥ID
*/
public static final String ACCESS_KEY = "XXXX";
/**
* secret_key 访问密钥
*/
public static final String SECRET_KEY = "XXXX";
/**
* bucket_name 桶名
*/
public static final String BUCKET_NAME = "XXXX";
/**
* 文件夹
*/
static final String PATH="images/";
static final BasicAWSCredentials awsCreds = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);
static final AmazonS3 s3 = AmazonS3ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(awsCreds))
//设置服务器所属地区
.withRegion(Regions.AP_SOUTHEAST_1)
.build();
/**
* 上传到文件返回一个文件储存后的路径
* @param multipartFile 文件内容
* @param bizPath 文件路径
* @return
* @throws Exception
*/
public static String uploadFile(MultipartFile multipartFile, String bizPath) {
if (multipartFile.isEmpty()) {
return "文件为空";
}
// 生成唯一的文件名
String MD5File = UUID.randomUUID().toString().replace("-", "");
String s3FilePath =PATH + bizPath + "/" + MD5File;
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentType(multipartFile.getContentType());
metadata.setContentLength(multipartFile.getSize());
try {
// 上传文件
PutObjectResult putObjectResult=s3.putObject(new PutObjectRequest(BUCKET_NAME, s3FilePath, multipartFile.getInputStream(), metadata)
.withCannedAcl(CannedAccessControlList.PublicRead));
putObjectResult.getContentMd5();
} catch (Exception e) {
e.printStackTrace();
}
//返回文件位置(桶名+文件路径)
return "https://XXXXXXX/"+s3FilePath;
}
/**
* 根据文件路径获取文件下载地址
* @param path
* @return
*/
public static String downloadFile(String path){
try {
GeneratePresignedUrlRequest httpRequest = new GeneratePresignedUrlRequest(BUCKET_NAME, path);
return s3.generatePresignedUrl(httpRequest).toString()+path;
}catch (Exception e){
e.printStackTrace();
}
return "获取失败";
}
}
/**
* 批量上传图片
*/
@PostMapping("/uploads")
public AjaxResult uploads(@RequestParam("file") MultipartFile[] multipartFile) throws Exception {
return tHeroesService.uploads(multipartFile);
}
总结
1.阿里云仓库可能会下不下来s3的依赖,从s3 的服务地址去下载。