赞
踩
最近因为项目原因,需要将程序下载到本地的图片上传到aws s3提供给国外的客户使用,下面是我用到的代码:
连接aws s3:
BasicAWSCredentials awsCreds = new BasicAWSCredentials(Access key ID, Secret access key);
AmazonS3 s3 = AmazonS3ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(awsCreds))
.withRegion(Regions.US_EAST_2)
.build();
这一步首先要确定你的s3上面有可使用的bucket。(列出s3上所有bucket的代码会在文后给出)
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentType("image/"+type); //type为设置上传图片的类型,jpg、png,如果不设置下载下来使用是会打不开
FileInputStream inputStream = new FileInputStream(path); //path为本地保存图片的路径,eg: E:/test.jpg
s3.putObject(bucket_name, key, inputStream, metadata); //key代表你上传的文件的唯一标识
确认图片是否已经上传到对应的bucket里。
ObjectListing result = s3.listObjects(bucket_name);
List<S3ObjectSummary> objects = result.getObjectSummaries();
System.out.println(objects.size());
for (S3ObjectSummary os: objects) {
System.out.println("listObjects* " + os.getKey()+"====="+os.getLastModified());
}
下面是其他代码:
//获取s3上面所有的buckets;
List<Bucket> buckets = s3.listBuckets();
System.out.println("Your Amazon S3 buckets are:");
System.out.println(buckets.size());
for (Bucket b : buckets) {
System.out.println("* " + b.getName());
}
将s3图片下载到本地(可以用于验证自己上传的图片是否可以使用)
public static void amazonS3Downloading(AmazonS3 s3Client,String bucketName,String key,String targetFilePath){
S3Object object = s3Client.getObject(new GetObjectRequest(bucketName,key));
if(object!=null){
System.out.println("Content-Type: " + object.getObjectMetadata().getContentType());
//InputStream input = null;
FileOutputStream fileOutputStream = null;
byte[] data = null;
S3ObjectInputStream input = null;
try {
//获取文件流
input = object.getObjectContent();
data = new byte[input.available()];
System.out.println(data.length);
int len = 0;
String path = targetFilePath + "/" + key;
File file = new File(path);
fileOutputStream = new FileOutputStream(file);
while ((len = input.read(data)) != -1) {
fileOutputStream.write(data, 0, len);
}
System.out.println("下载文件成功");
} catch (IOException e) {
e.printStackTrace();
}finally{
if(fileOutputStream!=null){
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(input!=null){
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
测试下载代码:
amazonS3Downloading(s3, bucket_name,key, "E:/test");
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。