Uploading File with REST API

There are multiple ways to upload files using REST API in Spring. Due to client limitations, it can happen that one ways is not enough and we need to provide multiple ways to upload files.

We are going to create REST API that reads file which has been upload and returns its content.

Using multipart/form-data

The most standard way to upload way is to use multipart.

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
public class UploadController {

  @PostMapping("/upload/multipart/form-data")
  public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file) throws IOException {
    byte[] bytes = file.getBytes();
    String fileContent = new String(bytes);
    return ResponseEntity.status(HttpStatus.CREATED).body(fileContent);
  }
}

Here is curl command that will upload a file.

Here is how we could test the code to verify functionality.

Here is the configuration file that will increase max allowed size of uploaded file, changes port and context path, configures logging output file and level.

Using application/x-www-form-urlencoded

Other way is to use application/x-www-form-urlencoded, usually sent from web clients.

Here is curl command that will upload a file using this REST API endpoint.

Here is how we could test the code to verify functionality.

Using application/octet-stream

The file is set into body and needs to be obtained from it.

Here is curl command that will upload a file using this REST API endpoint.

Here is how we could test the code to verify functionality.

Last updated

Was this helpful?