Amazon Web Services (AWS) S3 Java create a sub directory (object)

前端 未结 6 1206
孤城傲影
孤城傲影 2021-01-31 17:24

I am familiar with AWS Java SDK, I also tried to browse the corresponding Javadoc, but I could not realize how do I create a sub directory, i.e., a directory object within a buc

6条回答
  •  北恋
    北恋 (楼主)
    2021-01-31 18:14

    This worked for me. I used spring boot and file uploaded according to Multipart mechanism. I wanted to save my images inside the photos folder in my aws s3 bucket. My need is save like this photos/mypic.jpg

    ----controller class method----

    @PostMapping("/uploadFile")
        public String uploadFile(@RequestPart(value = "file") MultipartFile file) throws IOException {
            return this.amazonClient.uploadFile(file);
    }
    

    ----service class (Implementation of controller)----

     public String uploadFile(MultipartFile multipartFile) throws IOException {
        
                try {
                    File file = convertMultiPartToFile(multipartFile);
                    String fileName = "photoes/"+generateFileName(multipartFile);  //here give any folder name you want
                    uploadFileTos3bucket(fileName, file);
                } catch (AmazonServiceException ase) {
                    logger.info("Caught an AmazonServiceException from GET requests, rejected reasons:");
                }
                return fileName;
            }
    

    The point is concatenate the folder name you want as prefix of the fileName

    additionally I will show you how to delete folder. The point is give the folder name as the keyName(key name is uploaded object name in the s3 bucket.). I will show code snippet also.

    ----controller class method----

    @DeleteMapping("/deleteFile")
        public String deleteFile(@RequestPart(value = "keyName") String keyName) {
            return this.amazonClient.deleteFile(keyName);
        }
    

    ----service class (Implementation of controller)----

     public String deleteFile(String keyName){
            try {
                s3client.deleteObject(new DeleteObjectRequest(bucketName, keyName));
            } catch (SdkClientException e) {
                e.printStackTrace();
            }
            return "deleted file successfully!";
        }
    

    for delete photos folder that we created , call method like this. deleteFile("photos/") important:- / is mandatory

提交回复
热议问题