赞
踩
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-s3</artifactId>
<version>1.12.632</version>
</dependency>
import com.amazonaws.auth.AWSCredentials; 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.ObjectMetadata; import com.amazonaws.services.s3.model.PutObjectResult; import com.amazonaws.services.s3.model.S3Object; import com.amazonaws.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; /** * bucketName 存储桶(开头结尾都不带 '/', eg: ddd) * key 路径(开头不带 '/', eg: product/test/xxx) */ public class AmazonS3Util { private static final Logger log = LoggerFactory.getLogger(AmazonS3Util.class); private static final AWSCredentials credentials = new BasicAWSCredentials("s3_access_key", "s3_secret_key"); private static final AmazonS3 s3Client = AmazonS3ClientBuilder .standard() .withCredentials(new AWSStaticCredentialsProvider(credentials)) .withRegion(Regions.US_EAST_1) .build(); /** * 上传 */ public static boolean putObject(String bucketName, String key, String content) { byte[] contentBytes = content.getBytes(StringUtils.UTF8); InputStream input = new ByteArrayInputStream(contentBytes); return putObject(bucketName, key, input); } public static boolean putObject(String bucketName, String key, InputStream inputStream) { ObjectMetadata metadata = new ObjectMetadata(); try { metadata.setContentLength(inputStream.available()); } catch (IOException e) { throw new RuntimeException(e); } PutObjectResult result = s3Client.putObject(bucketName, key, inputStream, metadata); return result != null && !result.getVersionId().isEmpty(); } /** * 查询 */ public static S3Object getObject(String bucketName, String key) { if (s3Client.doesObjectExist(bucketName, key)) { return s3Client.getObject(bucketName, key); } return null; } public static String getObjectAsString(String bucketName, String key) { if (s3Client.doesObjectExist(bucketName, key)) { return s3Client.getObjectAsString(bucketName, key); } return null; } /** * 删除 */ public static void deleteObject(String bucketName, String key) { s3Client.deleteObject(bucketName, key); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。