ASW的S3上传文件(java)

将业务的代码简化一下,写成一个带页面方便测试的小demo.

首先用的spring boot项目,在resources文件夹下的static文件夹下创建一个index.html页面,用于简单的文件上传,html页面如下:




    
    文件上传


测试文件上传接口使用:
文件:

启动项目,访问页面:

ASW的S3上传文件(java)_第1张图片

虽然比较丑,但还可以将就着用 = =

接着写Controller层的代码:


@Slf4j
@RequestMapping("/uploadTest")
public class UploadController {


    private String accessKeyID ="accessKeyID";

    private String secretKey = "secretKey";
    //S3上桶的名称
    private String bucketName = "bucketName";
    //所属地区
    private String region = "region";

    /**
     * 上传文件
     * @param multipartFile
     * @return
     * @throws Exception
     */
    @RequestMapping("/uploadFile")
    public String uploadFile(@RequestParam("file") MultipartFile multipartFile) throws Exception {
        if (multipartFile.isEmpty()) {
            return "上传文件不能为空";
        }
        //生成随机文件名
        String localFileName = UUID.randomUUID() + "." + multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".") + 1);
        Date date = new Date();
        SimpleDateFormat formatter_yyyy = new SimpleDateFormat("yyyy");
        SimpleDateFormat formatter_MM = new SimpleDateFormat("MM");
        //在随机名前加上年月
        String s3FileFullPath = formatter_yyyy.format(date) + "/" + formatter_MM.format(date) + "/" + localFileName;

        //获取S3Client对象
        AWSCredentials awsCredentials = new BasicAWSCredentials(accessKeyID, secretKey);
        AmazonS3ClientBuilder builder = AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(awsCredentials));
        builder.setRegion(region);
        AmazonS3 s3Client = builder.build();

        ObjectMetadata metadata  = new ObjectMetadata();
        metadata.setContentType(multipartFile.getContentType());
        metadata.setContentLength(multipartFile.getSize());
        try {
            //开始上传文件
            //s3FileFullPath作为该文件的唯一标识符key
            PutObjectResult putResult = s3Client.putObject(bucketName, s3FileFullPath, multipartFile.getInputStream(), metadata);
            System.out.println("【流方式】上传MumbaiS3完成,md5:" + putResult.getETag() + ",S3文件:" + s3FileFullPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //返回文件在S3上的key
        return s3FileFullPath;
    }


}

然后我们随便选一个图片上传,发现控制台上打印出:

然后再去S3上相应的bucket上查看,发现有我们的图片.

到此,S3文件上传功能完成.

 

你可能感兴趣的:(ASW的S3上传文件(java))