簡體   English   中英

如何使用 java 在 amazon s3 中存儲文件

[英]How to store a file in amazon s3 using java

我是 s3 的新手,我需要一些幫助/

1.我從 rest api 得到一些文件,它看起來像

@PostMapping ("/aaa")
  public void aaa(@RequestParam("file")MultipartFile file)

我怎么能把它放到s3而不像這樣保存在本地

File f=new File(System.getProperty("java.io.tmpdir")+"/"+file.getOriginalFilename());
    file.transferTo(f);
    s3client.putObject("netapi", file.getOriginalFilename(),f);

我需要按原樣放置文件-例如,我將 img.png 放入 rest api 並且我需要從 s3 獲取鏈接到能夠下載和打開而無需在客戶端 pc 上進行任何轉換的同一文件

2.第二個問題是有什么方法可以不在 rest api 中使用 MultipartFile - 可能有一種方法可以將我可以從 HttpServletRequest.getInputStream() 獲取的 inputStream 轉換為具有相同文件名和文件擴展名的文件

我將 sdk 用於 java 1.X

implementation(group = "com.amazonaws",name="aws-java-sdk-s3",version = "1.11.1008")

要回答有關使用 Spring Controller 的問題,您可以獲得代表文件的字節數組,如下所示:

//Upload an image to send to a S3 bucket
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public ModelAndView singleFileUpload(@RequestParam("file") MultipartFile file) {

        try {

            // Now i can add this to an S3 Bucket
            byte[] bytes = file.getBytes();
            String name =  file.getOriginalFilename() ;

           // Put the file into the bucket
            s3Client.putObject(bytes, "mybucket", name);
       
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ModelAndView(new RedirectView("photo"));
    }

您可以使用該字節數組和文件名將文件放入 Amazon S3 存儲桶,而無需將其保存為本地文件。

要將其放入亞馬遜 S3 存儲桶,您可以使用以下代碼:

     // Places the file into a S3 bucket
     public String putObject(byte[] data, String bucketName, String objectKey) {
    
            s3 = getClient();
    
            try {
                //Put a file into the bucket
                PutObjectResponse response = s3.putObject(PutObjectRequest.builder()
                                .bucket(bucketName)
                                .key(objectKey)
                                .build(),
                        RequestBody.fromBytes(data));
    
                return response.eTag();
    
            } catch (S3Exception e) {
                System.err.println(e.getMessage());
                System.exit(1);
            }
            return "";
        }

 private S3Client getClient() {
        // Create the S3Client object
        Region region = Region.US_WEST_2;
        S3Client s3 = S3Client.builder()
                .credentialsProvider(EnvironmentVariableCredentialsProvider.create())
                .region(region)
                .build();

        return s3;
    }

此代碼向您展示如何處理發布到 Spring BOOT controller 的文件,如何獲取文件名和字節數組,以及如何使用 V2 S3 代碼將文件放入 Amazon S3 存儲桶。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM