Amazon S3 – Delete File SpringBoot RestAPI

In the tutorial, we build a SpringBoot RestAPIs to Delete files in a Amazon S3 bucket.

Previous post:
Amazon S3 – SpringBoot RestAPIs Upload/Download File/Image to S3

Technologies

  • Java 8
  • Maven 3.6.1
  • Spring Tool Suite: 3.9.4.RELEASE
  • Spring Boot: 2.0.4.RELEASE
  • Amazon S3

AmazonS3 Delete File API

We use delete API in com.amazonaws.services.s3.AmazonS3.java ->


public void deleteObject(DeleteObjectRequest deleteObjectRequest)
	throws SdkClientException, AmazonServiceException;
  • @param deleteObjectRequest: The request object containing all options for deleting an Amazon S3 object.
  • @throws SdkClientException: If any errors are encountered in the client while making the request or handling the response.
  • @throws AmazonServiceException: If any errors occurred in Amazon S3 while processing the request.

Practice

We re-use all the sourcecode of the previous tutorial:

-> Amazon S3 – SpringBoot RestAPIs Upload/Download File/Image to S3

spring-boot-restapi-delete-files-amazon-s3 + project-structure

What we build more? ->

  • Implement deleteFile service
  • Expose deleteFile RestAPI

Implement S3 Delete Files service

– Add deleteFile function in S3Services.java interface:


package com.ozenero.s3.services;

import java.io.ByteArrayOutputStream;
import java.util.List;

import org.springframework.web.multipart.MultipartFile;

public interface S3Services {

	...
	public void deleteFile(String keyName);
}

– Implement deleteFiles in S3ServicesImpl.java:


package com.ozenero.s3.services.impl;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.DeleteObjectRequest;

...
 
@Service
public class S3ServicesImpl implements S3Services {
	
	private Logger logger = LoggerFactory.getLogger(S3ServicesImpl.class);
	
	@Autowired
	private AmazonS3 s3client;
 
	@Value("${gkz.s3.bucket}")
	private String bucketName;
 
	...
	
	@Override
	public void deleteFile(String keyName) {
        try {
            s3client.deleteObject(new DeleteObjectRequest(bucketName, keyName));
        } catch(AmazonServiceException ase) {
        	logger.info("Caught an AmazonServiceException from PUT requests, rejected reasons:");
			logger.info("Error Message:    " + ase.getMessage());
			logger.info("HTTP Status Code: " + ase.getStatusCode());
			logger.info("AWS Error Code:   " + ase.getErrorCode());
			logger.info("Error Type:       " + ase.getErrorType());
			logger.info("Request ID:       " + ase.getRequestId());
        	throw ase;
        } catch (SdkClientException sce) {
            logger.info("Caught an SdkClientException: ");
            logger.info("Error Message: " + sce.getMessage());
            throw sce;
        }
	}
}

Expose Delete Files RestAPI

Create DeleteFileController controller ->


package com.ozenero.s3.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.ozenero.s3.services.S3Services;

@RestController
public class DeleteFileController {
	
	@Autowired
	S3Services s3Services;
	
    @DeleteMapping("/api/file/delete/{keyname}")
    public String uploadMultipartFile(@PathVariable String keyname) {
    	try {
    		s3Services.deleteFile(keyname);	
    	}catch(Exception e) {
    		return "Cannot Delete File -> Keyname = " + keyname;
    	}
    	return "Delete Successfully -> Keyname = " + keyname;
    }    
}

Run & Check results

Build & Run the SpringBoot sourcecode with commandlines {mvn clean install, mvn spring-boot:run}.

– File on Amazon S3 ->

spring-boot-restapi-delete-files-amazon-s3 + upload-file-on-s3

– Delete File:

spring-boot-restapi-delete-files-amazon-s3 + delete-file-on-s3

SourceCode

– In application.properties file, change gkz.aws.access_key_id & gkz.aws.secret_access_key to yours.

– Sourcecode -> SpringS3Amazon

Leave a Reply

Your email address will not be published. Required fields are marked *