0

I have a jsp file in which i am uploading a file. For backend handling of file i made a controller in spring. But it return error in console: String parameter 'name' is not present ? My Code is -

JSP File

<input class="fileInput" type="file" id="fileInput" accept="image/gif, image/jpeg, image/png" />
<button type="button" ng-click="saveProfile()">Update</button>

JS File

$scope.username = 01238339595;
$scope.saveProfile = function() {
                    var input = document.getElementById('fileInput');
                    if (input.files && input.files[0]) {
                        var formData = new FormData();
                        formData.append("name", $scope.username);
                        formData.append("file", input.files[0]);
                        console.log("form data " + formData);
                        $http.post("save-avatar", formData)
                            .success(function(data, status, headers,config) {
                                                        console.log('Success');
                                                    })
                            .error(function(data, status, headers, config) {
                                                        console.log('Error');
                                                    });
                    }
                };

Controller

@RequestMapping(value = "save-avatar", method = RequestMethod.POST)
public String handleFormUpload(@RequestParam("name") String name, @RequestParam("file") MultipartFile file,
        HttpServletRequest request) throws IOException {
    if (file.isEmpty())
        throw new IOException("File Field is Empty");

    ServletContext servletContext = request.getSession().getServletContext();
    String absoluteDiskPath = servletContext.getRealPath("/");

    File folder = new File(absoluteDiskPath + "/avatar/");
    if (!folder.exists())
        folder.mkdirs();

    File avatarFile = new File(folder, name + ".jpg");
    if (!avatarFile.exists())
        avatarFile.createNewFile();

    FileOutputStream outputStream = null;
    try {
        outputStream = new FileOutputStream(avatarFile);
        outputStream.write(file.getBytes());
    } finally {
        if (outputStream != null)
            outputStream.close();
    }

    return "redirect:/avatar-profile?name=" + name;
}

In my config xml:

<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="10485760" />
</bean>
1
  • thanks to @Rossi for the controller. On the rest, just change JS code to $http.post("save-avatar", formData, { transformRequest: angular.identity, headers: {'Content-Type': undefined} }) Commented Sep 26, 2015 at 4:15

1 Answer 1

1

Instead of the above controller method, use this:

@RequestMapping(value = "/save-avatar", method = RequestMethod.POST)
public void UploadFile(MultipartHttpServletRequest request, HttpServletResponse response) {

    Iterator<String> itr = request.getFileNames();
    MultipartFile file=null;

    while (itr.hastNext()) {
        file = request.getFile(itr.next());
        String name = request.getParameter("name");

        //Do your stuff here.......
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

excuse me. I have followed your instruction but it return org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateException: Current request is not of type [org.springframework.web.multipart.MultipartHttpServletRequest]
Do you have this in the config?? <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/
Make sure you have right dependencies and config setup.
Can you share what you have for the dependency and in the config.xml?
okay, I edited it on above. I think the problem is JS Code. Is var formData = new FormData(); right? i think we need a multipart form data, not a normal form data

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.