1. 程式人生 > >ASW的S3上傳檔案(java)

ASW的S3上傳檔案(java)

將業務的程式碼簡化一下,寫成一個帶頁面方便測試的小demo.

首先用的spring boot專案,在resources資料夾下的static資料夾下建立一個index.html頁面,用於簡單的檔案上傳,html頁面如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>檔案上傳</title>
</head>
<body>
<form enctype="multipart/form-data" method="post" action="/fileUpload_i18n/uploadFile">
    測試檔案上傳介面使用:<br/>
    檔案:<input type="file" name="file"/>
    <input type="submit" value="上傳"/>
</form>
</body>
</html>

啟動專案,訪問頁面:

雖然比較醜,但還可以將就著用 = =

接著寫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檔案上傳功能完成.