emreturka
emreturka

Reputation: 876

Spring MVC File Upload null multipart data

I want to upload an image file to one location in my computer with Spring MVC. But when I chose the file I am getting NullPointerException error. Here is my codes;

@RequestMapping("/save-product")
public void saveFile(HttpServletRequest servletRequest,
        @ModelAttribute("uploadedFile") UploadedFile uploadedFile,
        BindingResult bindingResult, Model model) {

    MultipartFile multipartFile = uploadedFile.getMultipartFile();
    String fileName = multipartFile.getOriginalFilename();
    try {
        File file = new File(servletRequest.getServletContext().getRealPath("/home/mesud/springupload/"), fileName);
        multipartFile.transferTo(file);
    } catch (IOException e) {
        e.printStackTrace();
    }
}


<sf:form enctype="multipart/form-data" modelAttribute="uploadedFile">
                <fieldset >
                 <legend>Resim Yükle</legend>
                 <div id='progressBar'
                    style='height: 20px; border: 2px solid green; margin-bottom: 20px'>
                    <div id='bar' style='height: 100%; background: #33dd33; width: 0%'>
                    </div>
                </div>
                <input type="file" id=profilResim value="Profil Resmi" style="margin-bottom: 20px"/><br/>
              </fieldset>
</sf:form>

I am uploading file in onSelect function in Javascript. Here is my javascript method;

function uploadNext() {
        var xhr = new XMLHttpRequest();
        var fd = new FormData();
        var file = document.getElementById('profilResim').files[filesUploaded];
        fd.append("multipartFile", file);
        xhr.upload.addEventListener("progress", onUploadProgress, false);
        xhr.addEventListener("load", onUploadComplete, false);
        xhr.addEventListener("error", onUploadFailed, false);
        xhr.open("POST", "save-product");
        debug('uploading ' + file.name);
        xhr.send(fd);
    }

In my Applicaiton Initializer class I use this method for multipart requests;

@Override
protected void customizeRegistration(Dynamic registration) {
    registration.addMapping("/");
    registration.setMultipartConfig(new   MultipartConfigElement("/home/mesud/springtemp",2097152, 4194304, 0));
}

Why my UploadedFile object (this object is includes a MultipartFile object) is posted null?

Upvotes: 0

Views: 1347

Answers (1)

Saurabh Chaturvedi
Saurabh Chaturvedi

Reputation: 2176

There could be several reasons . Do some checks like have you defined CommonsMultiPartResolver bean in your application-context.xml file . If not define it . Also check your jars . Ensure you have commons-fileupload jar and commons-io jar . Let me know if that helped you.

Upvotes: 1

Related Questions