Springboot集成Amazon-S3对象存储桶与工具类实现
import com.amazonaws.auth.AWSCredentials;
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.PutObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
public class AwsS3Util {
private static final String ACCESS_KEY = "your-access-key-id";
private static final String SECRET_KEY = "your-secret-access-key";
private static final String BUCKET_NAME = "your-bucket-name";
private static final Regions region = Regions.US_EAST_1;
private static final AWSCredentials credentials = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);
private static final AmazonS3 s3client = AmazonS3ClientBuilder.standard()
.withRegion(region)
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.build();
public static void uploadFileToS3(String fileName, byte[] fileContent) {
ByteArrayInputStream bis = new ByteArrayInputStream(fileContent);
PutObjectRequest request = new PutObjectRequest(BUCKET_NAME, fileName, bis, null);
s3client.putObject(request);
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static byte[] downloadFileFromS3(String fileName) {
S3Object s3object = s3client.getObject(BUCKET_NAME, fileName);
S3ObjectInputStream s3is = s3object.getObjectContent();
byte[] fileContent = new byte[0];
try {
fileContent = new byte[s3is.available()];
s3is.read(fileContent);
} catch (IOException e) {
e.printStackTrace();
}
return fileContent;
}
}
这个代码实例提供了一个简单的工具类,用于与Amazon S3进行交互。它包括上传和下载文件的方法,并且使用静态初始化配置了Amazon S3客户端。在实际应用中,你需要替换your-access-key-id
、your-secret-access-key
和your-bucket-name
为你的AWS凭证和桶名称。此外,你可以根据需要调整代码,例如添加异常处理和日志记录。
评论已关闭