63

I am trying to make a restful controller to upload files. I have seen this and made this controller:

@RestController
public class MaterialController {

    @RequestMapping(value="/upload", method= RequestMethod.POST)
    public String handleFileUpload(
            @RequestParam("file") MultipartFile file){
        String name = "test11";
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                BufferedOutputStream stream =
                        new BufferedOutputStream(new FileOutputStream(new File(name + "-uploaded")));
                stream.write(bytes);
                stream.close();
                return "You successfully uploaded " + name + " into " + name + "-uploaded !";
            } catch (Exception e) {
                return "You failed to upload " + name + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload " + name + " because the file was empty.";
        }
    }
}

and then i used postman to send a pdf:

enter image description here

But the server crashes with the error:

.MultipartException: Current request is not a multipart request

Again i have found this, and added a bean.xml file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    </bean>
</beans>

Unfortunately, it still complains with the same error.

Sal-laS
  • 11,016
  • 25
  • 99
  • 169
  • Don't know if it's causing your problem, but the screenshot shows that you didn't name the *part*. According to your `handleFileUpload()` method, you need to give the *part* a name/key value of `file`. Without a *part* name, it probably didn't send anything to the server, and "nothing" = "not multipart". – Andreas Feb 02 '17 at 22:23
  • No, you shouldn't need to make a directory. – Andreas Feb 02 '17 at 22:27
  • *Unrelated:* Since you annotated class with `@RestController`, you don't need to annotate method with `@ResponseBody`. See javadoc: https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RestController.html – Andreas Feb 02 '17 at 22:29

13 Answers13

67

When you are using Postman for multipart request then don't specify a custom Content-Type in Header. So your Header tab in Postman should be empty. Postman will determine form-data boundary. In Body tab of Postman you should select form-data and select file type. You can find related discussion at https://github.com/postmanlabs/postman-app-support/issues/576

abaghel
  • 14,783
  • 2
  • 50
  • 66
  • I didn't get you. can you send an image of right request in postman. – Sal-laS Feb 03 '17 at 12:09
  • 2
    Check the Headers tab just before Body tab in Postman. Your request is correct but there is some entry in Headers as image shared by you shows Headers(1). Remove entry from there. – abaghel Feb 03 '17 at 12:12
16

It looks like the problem is request to server is not a multi-part request. Basically you need to modify your client-side form. For example:

<form action="..." method="post" enctype="multipart/form-data">
  <input type="file" name="file" />
</form>

Hope this helps.

Javier Z.
  • 784
  • 4
  • 10
15

I was also facing the same issue with Postman for multipart. I fixed it by doing the following steps:

  • Do not select Content-Type in the Headers section.
  • In Body tab of Postman you should select form-data and select file type.

It worked for me.

J-Alex
  • 6,881
  • 10
  • 46
  • 64
Nilesh Kumar
  • 151
  • 1
  • 2
14

That happened once to me: I had a perfectly working Postman configuration, but then, without changing anything, even though I didn't inform the Content-Type manually on Postman, it stopped working; following the answers to this question, I tried both disabling the header and letting Postman add it automatically, but neither options worked.

I ended up solving it by going to the Body tab, change the param type from File to Text, then back to File and then re-selecting the file to send; somehow, this made it work again. Smells like a Postman bug, in that specific case, maybe?

Haroldo_OK
  • 6,612
  • 3
  • 43
  • 80
5

In application.properties, please add this:

spring.servlet.multipart.max-file-size=128KB
spring.servlet.multipart.max-request-size=128KB
spring.http.multipart.enabled=false

and in your html form, you need an : enctype="multipart/form-data". For example:

<form method="POST" enctype="multipart/form-data" action="/">

Hope this help!

N.Luan Pham
  • 49
  • 1
  • 3
2

Check the file which you have selected in the request.

For me i was getting the error because the file was not present in the system, as i have imported the request from some other machine.

KayV
  • 12,987
  • 11
  • 98
  • 148
  • 1
    I had the exact problem! Every setting was correct - but one thing: The file did not exist (anymore). Instead of getting a 'file not found' (or something similar) I would always get `Current request is not a multipart request`. – cheneym Aug 12 '20 at 12:48
2

In my case, I removed:

'Content-Type': 'application/json',

from my Interceptor, and everything works.

     intercept(httpRequest: HttpRequest<any>, httpHandler: HttpHandler): Observable<HttpEvent<any>> {
if (this.authService.isUserLoggedIn() && httpRequest.url.indexOf('login') === -1) {
  const authReq = httpRequest.clone({
    headers: new HttpHeaders({
    'Content-Type': 'application/json',
      Authorization: this.authService.getBasicAuth()
    })
  });
  return httpHandler.handle(authReq);
} else {
  return httpHandler.handle(httpRequest);
}}
mzhehalo
  • 78
  • 9
2

You need to add consumes = {MULTIPART_FORM_DATA_VALUE} to your mapping. Full example :

@PostMapping(path = "/{idDocument}/attachments", consumes = {MULTIPART_FORM_DATA_VALUE})
ResponseEntity<String> addAttachmentsToDocumentForm(@PathVariable Long idDocument, @RequestParam("file") MultipartFile[] files){
    documentService.addAttachments(idDocument, files);
    return ok("your response");
}
Tomasz
  • 884
  • 8
  • 12
2

enter image description here

 @PostMapping("/upload")
  public ResponseEntity<ResponseMessage> uploadFile(@RequestParam("file") MultipartFile uploadFile) {
    String message = "";
    try {
        service.save(uploadFile);

      message = "Uploaded the file successfully: " + uploadFile.getOriginalFilename();
      return ResponseEntity.status(HttpStatus.OK).body(new ResponseMessage(message));
    } catch (Exception e) {
      message = "Could not upload the file: " + uploadFile.getOriginalFilename() + "!";
      return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ResponseMessage(message));
    }
  }
Ravi
  • 338
  • 1
  • 12
1

in ARC (advanced rest client) - specify as below to make it work Content-Type multipart/form-data (this is header name and header value) this allows you to add form data as key and values you can specify you field name now as per your REST specification and select your file to upload from file selector.

Pravin Bansal
  • 4,315
  • 1
  • 28
  • 19
0

i was facing the same issue with misspelled enctype="multipart/form-data", i was fix this exception by doing correct spelling . Current request is not a multipart request client side error so please check your form.

0

i was facing this issue but it was due to the file i was uploading in postman wasn't in the postman working directory Go to Settings -> General and scroll down to location to find it's location folder and put your files to upload there.

See : Setup Potman working directory

Youngkhaf
  • 11
  • 1
0

add required=false with the parameter @RequestParam(required = false,value = "file") MultipartFile file

  • 1
    Welcome to SO! Please add a little textual explanation about how and why your approach works and what makes it different from the other answers given. You can find out more at our ["How to write a good answer"](https://stackoverflow.com/help/how-to-answer) page. Additionally, in my opionen, what you wrote does not answer the question as there is a different problem. – ahuemmer Aug 04 '22 at 13:42