最新消息:文章中包含代码时,请遵守代码高亮规范!

Aws的S3上传文件

Java 姚, 伟 254浏览 0评论
public static String uploadFile(MultipartFile file) {
    if (file.isEmpty()) {
        return "上传文件不能为空";
    }

    String fileName = String.valueOf(System.currentTimeMillis()) + S3Constant.IMG_TYPE;

    //获取S3Client对象
    BasicAWSCredentials credentials = new BasicAWSCredentials(S3Constant.ACCESS_KEY, S3Constant.SECRET_KEY);
    AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
            .withRegion(Regions.US_EAST_1)
            .withCredentials(new AWSStaticCredentialsProvider(credentials))
            .build();

    ObjectMetadata metadata = new ObjectMetadata();
    metadata.setContentType(file.getContentType());
    metadata.setContentLength(file.getSize());
    try {
        //开始上传文件
        s3Client.putObject(new PutObjectRequest(S3Constant.BUCKET_NAME, fileName, file.getInputStream(), metadata)
                .withCannedAcl(CannedAccessControlList.PublicRead));
        log.info("【流方式】S3文件:" + fileName);
    } catch (Exception e) {
        log.info("error info:" + e);
    }
    //返回文件在S3上的key
    return S3Constant.PATH + fileName;
}

转载时请注明出处及相应链接,本文永久地址:http://blog.meken.net/24638.html


pay_weixin
pay_weixin
微信打赏
pay_weixin
支付宝打赏
感谢您对作者van的打赏,我们会更加努力!    如果您想成为作者,请点我

您必须 登录 才能发表评论!