Search code examples
javaspring-mvchttp-request-parameters

MultipartFile returns null every time


I am using this code to post an image file to my controller but I always get a null value for the file body part.

@RequestMapping(value = "/updateprofile", method = RequestMethod.POST)
public @ResponseBody
ResponseMsg updateProfile(
        @RequestHeader(value = "userid", required = false) String userid,
        @RequestHeader(value = "name", required = false) String name,
        @RequestHeader(value = "phone", required = false) int phone,
        @RequestParam(value = "file", required = false) MultipartFile file) {

    ResponseMsg responseMsg = CommonUtils.checkParam(userid, name, phone,
            file);
    if (responseMsg.getStatus().equalsIgnoreCase("True"))
        responseMsg = userService.login(name, userid);
    return responseMsg;
}

Can anyone help with this?


Solution

  • When you use multipart then your form fields are included in request Stream. So you have to check whether they are form fields or not.

    This is what I use in a servlet, you can make appropriate changes in it to work in Spring-MVC.

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (isMultipart)
            {
                try 
                {
                    List items = upload.parseRequest(request);
                    Iterator iterator = items.iterator();
                    while (iterator.hasNext()) 
                    {
                        FileItem item = (FileItem) iterator.next();
    
                        if (item.isFormField()) //your code for getting form fields
                        {
                            String name = item.getFieldName();
                            String value = item.getString();
                            System.out.println(name+value);
                        }
    
                        if (!item.isFormField()) 
                        {
                           //your code for getting multipart 
                        }
                    }
                }