user1732653
user1732653

Reputation: 635

Spring - upload form - unable to get the file list

I am getting the below error while uploading the files (multiple files) using Spring MVC.

java.lang.NullPointerException
    com.mkyong.common.controller.FileUploadController.save(FileUploadController.java:34)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    java.lang.reflect.Method.invoke(Method.java:597)

jsp

<form:form method="post" action="save" 
        modelAttribute="uploadForm" enctype="multipart/form-data">
    <p>Select files to upload. Press Add button to add more file inputs.</p>
    <input id="addFile" type="button" value="Add File" />
    <table id="fileTable">
        <tr>
            <td><input name="files[0]" type="file" /></td>
        </tr>
        <tr>
            <td><input name="files[1]" type="file" /></td>
        </tr>
    </table>
    <br/><input type="submit" value="Upload" />
</form:form>

Controller

@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(
        @ModelAttribute("uploadForm") FileUploadForm uploadForm,
                Model map) {
    List<MultipartFile> files = uploadForm.getFiles();

    List<String> fileNames = new ArrayList<String>();
    //counting the file size
    System.out.println("Files count :"+files.size());

    if(null != files && files.size() > 0) { //HERE 'files' is NULL
        for (MultipartFile multipartFile : files) {

            String fileName = multipartFile.getOriginalFilename();
            fileNames.add(fileName);
            //Handle file content - multipartFile.getInputStream()

        }
    }

Can anyone please help me in fixing this? I am still debugging why I am not able to pass the files(uploadForm) from jsp to controller.

Upvotes: 2

Views: 3642

Answers (1)

MRX
MRX

Reputation: 1651

I just solved it. you need to add <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" /> in your dispatcher-servlet.xml.

and if you are using multipart array for multiple files then use just array name. like

private MultipartFile [] file;

Getters and Setters and in form

<form:form commandName="uploadFile" method="post" enctype="multipart/form-data">
        <input type="file" name="file"/>
        <input type="file" name="file"/>
        <input type="file" name="file"/>
        <input type="submit" value="Submit"/>
    </form:form>

Upvotes: 1

Related Questions