So this is the my Controller layer where i have created a method for deleteFiles from AWS and DataBase at the same time.
@RestController
@RequestMapping("/api/v1/images")
public class ImageController {
@DeleteMapping(path = "/delete/file/{bucketName}/{imageUrl}")
public ResponseEntity<String> deleteFile(@PathVariable String bucketName, @PathVariable String imageUrl) {
boolean isDeleted = imageService.deleteFile(bucketName, imageUrl);
if (isDeleted) {
return new ResponseEntity<>("File deleted successfully", HttpStatus.OK);
} else {
return new ResponseEntity<>("File deletion failed", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
**This is my Service layer – **
@Service
public class ImageService {
@Transactional
public boolean deleteFile(String bucketName, String imageUrl) {
try {
String fileName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
// Delete the file from S3 bucket
amazonS3.deleteObject(new DeleteObjectRequest(bucketName, fileName));
// Delete the file reference from the database
imagesRepository.deleteByImageUrl(imageUrl);
return true;
} catch (Exception e) {
return false;
}
}
}
**
I have created a Repository where i have build a query for deleting record form my data base -**
public interface ImagesRepository extends JpaRepository<Images, Long> {
@Modifying
@Transactional
@Query("DELETE FROM Images i WHERE i.imageUrl LIKE %:imageUrl%")
void deleteByImageUrl(@Param("imageUrl") String imageUrl);
}
Im trying to delete a record with this url –
URL – http://localhost:8080/api/v1/images/delete/file/airbnb-images/https://airbnb-images.s3.amazonaws.com/Manali2.jpg
Getting an Error in postman –
{
"timestamp": "2024-05-29T09:18:48.782+00:00",
"status": 400,
"error": "Bad Request",
"message": "No message available",
"path": "/api/v1/images/delete/file/airbnb-images/https://airbnb-images.s3.amazonaws.com/Manali2.jpg"
}
what should i have to do for a solution?
New contributor
study email is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.