首先加入pom中加入依赖
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-s3</artifactId>
<version>1.11.327</version>
</dependency>
然后这是我写的一个工具类
public class FileUtils {
//密匙
static final String ACCESS_KEY ="xxxxxxxxxxxxxxxxx";
static final String SECRET_KEY = "xxxxxxxxxxxxxxxxxx";
//储存桶的名称
static final String BUCKET_NAME = "xxxxxxxxx";
//所属地区
static final String REGION = "us-west-2";
//储存路径,不同太在意我的,填你自己想要储存的路径
static final String PATH="giftImage";
static final BasicAWSCredentials awsCreds = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);
static final AmazonS3 s3 = AmazonS3ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(awsCreds))
//设置服务器所属地区
.withRegion(REGION)
.build();
/**
* 上传到文件返回一个文件储存后的路径
* @param multipartFile
* @return
* @throws Exception
*/
public static String uploadFile(MultipartFile multipartFile) {
if (multipartFile.isEmpty()) {
return "文件为空";
}
Date date = new Date();
SimpleDateFormat formatter_yyyy = new SimpleDateFormat("yyyy");
SimpleDateFormat formatter_MM = new SimpleDateFormat("MM");
//在随机名前加上年月
String s3FilePath =PATH + "/" +formatter_yyyy.format(date) + "/" + formatter_MM.format(date) + "/" + multipartFile.getOriginalFilename();
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentType(multipartFile.getContentType());
metadata.setContentLength(multipartFile.getSize());
try {
//开始上传文件
PutObjectResult putObjectResult=s3.putObject(BUCKET_NAME, s3FilePath, multipartFile.getInputStream(), metadata);
System.err.println("上传完成__文件位置为" + putObjectResult);
} catch (Exception e) {
e.printStackTrace();
}
//返回文件位置
return 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 "获取失败";
}
}