javaamazon-web-servicesspring-bootapiamazon-s3

Problem with file directory link in amazon s3


Basically I have a product registration api, and in that api in my post, I send json information to my database and upload the product image which is stored in my amazon s3 and its directory link is saved in "image_url" in the product database.

But I save the link exactly like this:

productModel.setImage_url("https://" + BUCKET_NAME + ".s3.amazonaws.com" + fileName);

So I see that this is problematic, because I'm trying with my delete method to delete the image sent inside the database and I'm not succeeding

    @DeleteMapping("/{id}")
    public ResponseEntity<Object> deleteProduct(@PathVariable(value = "id") UUID id) {
        Optional<ProductModel> productModelOptional = productService.findById(id);
        if (!productModelOptional.isPresent()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Product not found!");
        }
        ProductModel productModel = productModelOptional.get();

        String imageUrl = productModel.getImage_url();

        try {
            DeleteObjectRequest deleteObjectRequest = DeleteObjectRequest.builder()
                    .bucket(BUCKET_NAME)
                    .key(imageUrl)
                    .build();

            s3Client.deleteObject(deleteObjectRequest);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.CONFLICT).body(e);
        }
        productService.delete(productModelOptional.get());
        return ResponseEntity.status(HttpStatus.OK).body("Product deleted succesfully!");
    }
}

I thought I might be sending the link wrong somehow, but logging into my amazon s3 and clicking on the image link itself I am taken to a page with the message:

This XML file does not appear to have any style information associated with it. The document tree is shown below.

There's something wrong and I don't know what it is


Solution

  • In S3 there are buckets and keys. The key is the file name, including the "folder". It is not the entire URL. A key may be something like folder1/folder2/filename.txt. So for your code, delete with:

    String imageUrl = productModel.getImage_url();
    
    // extract the file name from the imageUrl.  This may be as simple
    // as finding the last forward slash or it may be something stored
    // in your ProductModel object
    
    String objectKey = ...
    
    try {
        DeleteObjectRequest deleteObjectRequest = DeleteObjectRequest.builder()
                .bucket(BUCKET_NAME)
                .key(objectKey)  // delete by the key
                .build();
    
        s3Client.deleteObject(deleteObjectRequest);
    } catch (Exception e) {
        return ResponseEntity.status(HttpStatus.CONFLICT).body(e);
    }