spring-mvc File Upload Uploading a single file


To receive a file uploaded via an HTTP Post, you need to do the following:

    value = "...",
    method = RequestMethod.POST,
    consumes = MediaType.MULTIPART_FORM_DATA_VALUE
public Object uploadFile(
    @RequestPart MultipartFile file
) {
    String fileName = file.getOriginalFilename();
    InputStream inputStream = file.getInputStream();
    String contentType = file.getContentType();

Note that the name of the @RequestPart parameter needs to match up with the name of the part in the request.


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

As HTML (Spring TagLibs):

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

As a raw HTTP request:

POST /... HTTP/1.1
Host: ...
Content-Type: multipart/form-data; boundary=----------287032381131322

Content-Disposition: form-data; name="file"; filename="r.gif"
Content-Type: image/gif


That request would mean the following:

fileName == "r.gif"
contentType == "image/gif"

In Spring MVC

Need to add the mentioned bean for accessing multipart functionality

    <!-- max size of file in memory (in bytes) -->
    <property name="maxInMemorySize" value="1048576" /> <!-- 1MB -->