繁体   English   中英

Spring Boot + AWS S3:无法删除存储桶中的文件

[英]Spring Boot + AWS S3: Unable to delete files in the bucket

我是 AWS 的新手,我尝试学习的第一个模块是用于文件存储的 S3。

上传工作正常,问题在于删除。因此,当我上传文件时,我将文件名称的字符串版本存储在 AWS 存储桶mybucket ,并将整个 URL 存储在 mysql 数据库中,如下所示 -> https://mybucket.s3.eu-west-2.amazonaws.com/what.png

删除的问题是,即使我在这种情况下将整个 URL https://mybucket.s3.eu-west-2.amazonaws.com/what.png传递给 delete 方法,该方法也会成功地执行每个步骤,告诉我文件已成功删除,但是当我检查存储桶时,文件仍然存在。我尝试在此处搜索类似问题,但找不到可以帮助我了解问题所在的内容。此处是代码

@Service
public class AmazonS3ClientServiceImpl {
    private String awsS3AudioBucket; //bucket name
    private AmazonS3 amazonS3; // s3 object which uploads file
    private static final Logger logger = LoggerFactory.getLogger(AmazonS3ClientServiceImpl.class);

    @Autowired
    public AmazonS3ClientServiceImpl(Region awsRegion, AWSCredentialsProvider awsCredentialsProvider, String awsS3AudioBucket) {
        this.amazonS3 = AmazonS3ClientBuilder.standard()
                .withCredentials(awsCredentialsProvider)
                .withRegion(awsRegion.getName()).build();
        this.awsS3AudioBucket = awsS3AudioBucket;
    }


    public String uploadFileToS3Bucket(MultipartFile multipartFile, boolean enablePublicReadAccess) {
        String uploadedfile = ""; // the file path which is on s3
        String fileName = multipartFile.getOriginalFilename();

        try {
            //creating the file in the server (temporarily)
            File file = new File(fileName);
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(multipartFile.getBytes());
            fos.close();

            PutObjectRequest putObjectRequest = new PutObjectRequest(this.awsS3AudioBucket, fileName, file);

            if (enablePublicReadAccess) {
                putObjectRequest.withCannedAcl(CannedAccessControlList.PublicRead);
            }
            this.amazonS3.putObject(putObjectRequest);
            uploadedfile = String.valueOf(this.amazonS3.getUrl(awsS3AudioBucket, fileName));
            System.out.println(this.amazonS3.getUrl(awsS3AudioBucket, fileName));
            System.out.println(uploadedfile);


            //removing the file created in the server
            file.delete();
        } catch (IOException | AmazonServiceException ex) {
            logger.error("error [" + ex.getMessage() + "] occurred while uploading [" + fileName + "] ");
        }
        return uploadedfile;
    }

    public void deleteFileFromS3Bucket(String fileName) {
        LOGGER.info("Deleting file with name= " + fileName);
        final DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest(this.awsS3AudioBucket, fileName);
        amazonS3.deleteObject(deleteObjectRequest);
        LOGGER.info("File deleted successfully");
    }

当我调用 deletemethod 时,我使用它

@GetMapping("/dashboard/showposts/delete/{id}")
    public String deletePost(@PathVariable("id") Long id, Model model) {
        System.out.println("GOT HERE");
        //Retrieving Post image name
        Post post = postService.findBydId(id);
        String imageName = post.getImage();
        System.out.println(imageName);
        //Deleting image from S3 bucket
        amazonClient.deleteFileFromS3Bucket(imageName);
        //Deleting post from db
        postService.detelePost(id);
        String success = "Successfully deleted post with Id" + id;
        model.addAttribute("success", success);
        return "redirect:/admin/dashboard/showposts";
    }

任何帮助将不胜感激。

LE对于有同样问题并正在寻找快速答案的任何人。您必须仅将字符串图像名称传递给删除方法,而不是整个 URL。

您不是在检查从amazonS3.deleteObject()返回的响应以查看它是否真的成功。 它可能正在返回失败状态。

我猜根本问题是您将完整的 URL 传递给 delete 方法,而不仅仅是 S3 中文件的路径。 例如,对于这个 URL: https://mybucket.s3.eu-west-2.amazonaws.com/what.png : what.png对象路径就是what.png

最简单的答案是使用URL类。 就像是:

    URL url = null;
    try {
        url = new URL("https://mybucket.s3.eu-west-2.amazonaws.com/some/path/what.png");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    System.out.println( "file is \""+ url.getFile() + "\"" );

输出将是“/some/path/what.png”。 您可以删除用于键的第一个“/”字符。

Aws S3 最终是一致的。 您可以删除对象并 s3 在浏览器中列出该对象。 因此删除 . 需要几秒钟或更短的时间。

请参考这个链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM