Spring Boot Delete File example

In previous post, we’ve known how to upload and download files with a Spring Boot Rest API. In this tutorial, I will continue to show you way to delete file (if it exists) in Spring Boot.

Related Posts:
– Using Template Engine: Spring Boot Delete File example with Thymeleaf
How to upload multiple files in Java Spring Boot
Spring Boot: Upload/Import Excel file data into MySQL Database
Spring Boot: Upload/Import CSV file data into MySQL Database

Deployment: Deploy Spring Boot App on AWS – Elastic Beanstalk


Spring Boot Rest API for deleting File

Our Spring Boot Application has already provided API for:

  • uploading File to a static folder in the Server
  • downloading File from server with the link
  • getting list of Files’ information (file name & url)
Methods Urls Actions
POST /upload upload a File
GET /files get List of Files (name & url)
GET /files/[filename] download a File

More details at: Spring Boot File upload/download example

Now we continue to provide new API for deleting file:

Methods Urls Actions
DELETE /files/[filename] delete a File

spring-boot-delete-file-rest-api-example

If the file that you want to delete does not exist:

spring-boot-delete-file-if-exists-example

Technology

  • Java 8
  • Spring Boot 2 (with Spring Web MVC)
  • Maven 3.6.1

Project Structure

We will add some functions to existing Spring Boot project:

spring-boot-delete-file-example-project

Let me explain it briefly.

FileInfo contains information of the uploaded file.
FilesStorageService helps us to initialize storage, save new file, load file, get list of Files’ info, delete files.
FilesController uses FilesStorageService to export Rest APIs including DELETE file API.
FileUploadExceptionAdvice handles exception when the controller processes file upload.
application.properties contains configuration for Servlet Multipart.
uploads is the static folder for storing files.
pom.xml for Spring Boot dependency.

Setup Spring Boot project

Use Spring web tool or your development tool (Spring Tool Suite, Eclipse, Intellij) to create a Spring Boot project.

Then open pom.xml and add these dependencies:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Or you can visit following tutorial for base project and Github source code:
Spring Boot File upload/download example

Create Service for File Storage

First we need an interface that will be autowired in the Controller.
In service folder, create FilesStorageService interface like following code:

service/FilesStorageService.java

package com.bezkoder.spring.files.upload.service;

import java.nio.file.Path;
import java.util.stream.Stream;

import org.springframework.core.io.Resource;
import org.springframework.web.multipart.MultipartFile;

public interface FilesStorageService {
  public void init();

  public void save(MultipartFile file);

  public Resource load(String filename);
  
  public boolean delete(String filename);

  public void deleteAll();

  public Stream<Path> loadAll();
}

Now we create implementation of the interface and override the method: boolean delete(String filename).

service/FilesStorageServiceImpl.java

package com.bezkoder.spring.files.upload.service;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
// ...
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.multipart.MultipartFile;

@Service
public class FilesStorageServiceImpl implements FilesStorageService {

  private final Path root = Paths.get("uploads");

  @Override
  public void init() {
    try {
      Files.createDirectories(root);
    } catch (IOException e) {
      throw new RuntimeException("Could not initialize folder for upload!");
    }
  }

  @Override
  public void save(MultipartFile file) {
    // ...
  }

  @Override
  public Resource load(String filename) {
    // ...
  }

  @Override
  public boolean delete(String filename) {
    try {
      Path file = root.resolve(filename);
      return Files.deleteIfExists(file);
    } catch (IOException e) {
      throw new RuntimeException("Error: " + e.getMessage());
    }
  }

  @Override
  public void deleteAll() {
    FileSystemUtils.deleteRecursively(root.toFile());
  }

  @Override
  public Stream<Path> loadAll() {
    // ...
  }
}

delete() method receives the filename parameter, converts a given that file string to a Path object using Path.resolve().

Then we use static method Files.deleteIfExists() to delete that file by its corresponding Path object.
Files.deleteIfExists() will return:

  • true if the file was deleted successfully.
  • false if the file cannot be deleted because it does not exist

Define Response Message

The ResponseMessage is for message to client that we’re gonna use in Rest Controller and Exception Handler.

message/ResponseMessage.java

package com.bezkoder.spring.files.upload.message;

public class ResponseMessage {
  private String message;

  public ResponseMessage(String message) {
    this.message = message;
  }

  public String getMessage() {
    return message;
  }

  public void setMessage(String message) {
    this.message = message;
  }

}

Create Controller for Delete File

In controller package, we create FilesController.

controller/FilesController.java

package com.bezkoder.spring.files.upload.controller;

// ...
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;

import com.bezkoder.spring.files.upload.message.ResponseMessage;
import com.bezkoder.spring.files.upload.service.FilesStorageService;

@Controller
@CrossOrigin("http://localhost:8081")
public class FilesController {

  @Autowired
  FilesStorageService storageService;

  // ...

  @DeleteMapping("/files/{filename:.+}")
  public ResponseEntity<ResponseMessage> deleteFile(@PathVariable String filename) {
    String message = "";
    
    try {
      boolean existed = storageService.delete(filename);
      
      if (existed) {
        message = "Delete the file successfully: " + filename;
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseMessage(message));
      }
      
      message = "The file does not exist!";
      return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new ResponseMessage(message));
    } catch (Exception e) {
      message = "Could not delete the file: " + filename + ". Error: " + e.getMessage();
      return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ResponseMessage(message));
    }
  }
}

@CrossOrigin is for configuring allowed origins.
@Controller annotation is used to define a controller.
@DeleteMapping annotation is for mapping HTTP DELETE requests:

  • DELETE /files/[filename]: deleteFile()

– We use @Autowired to inject implementation of FilesStorageService bean to local variable.

Initialize Storage

We need to run init() method of FilesStorageService (and also deleteAll() if necessary). So open SpringBootUploadFilesApplication.java and implement CommandLineRunner for run() method like this:

package com.bezkoder.spring.files.upload;

import javax.annotation.Resource;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.bezkoder.spring.files.upload.service.FilesStorageService;

@SpringBootApplication
public class SpringBootUploadFilesApplication implements CommandLineRunner {
  @Resource
  FilesStorageService storageService;

  public static void main(String[] args) {
    SpringApplication.run(SpringBootUploadFilesApplication.class, args);
  }

  @Override
  public void run(String... arg) throws Exception {
//    storageService.deleteAll();
    storageService.init();
  }
}

Run the Spring Boot Delete File example

Run Spring Boot application with command: mvn spring-boot:run.

Source Code

You can find the complete source code for this tutorial on Github.

Using Template Engine: Spring Boot Delete File example with Thymeleaf

Conclusion

Today we’ve learned how to create Spring Boot Delete File example with static folder via Restful API.

For upload/download file Rest API, please visit:
Spring Boot File upload/download example

Or upload multiple Files at once:
How to upload multiple files in Java Spring Boot

You can also know way to upload an Excel/CSV file and store the content in MySQL database with the post:
Spring Boot: Upload/Import Excel file data into MySQL Database
Spring Boot: Upload/Import CSV file data into MySQL Database

If you want to store files in database like this:
spring-boot-upload-files-to-database-table-files

You can find instruction at:
Spring Boot Upload/Download File to/from Database example

Happy Learning! See you again.

Leave a Reply