views:

79

answers:

1

I am working on a Spring web application and need to implement a simple FileUpload for one of my pages.

The page for the JSP contains the following snippet of code which included an upload field for uploading the file.

<form:form commandName="editMemberInfoModelObj" method="post" enctype="multipart/form-data">
        <h1>Edit Member Information</h1>
        <table>
            //Other Form Input Fields ...
            <tr>
                <td>File</td>
                <td><input type="file" name="file"/></td>
            </tr>
            <tr>
                <td><input type="submit" value="Update Info"/></td>
            </tr>
        </table>
    </form:form>

The model for this JSP looks like the following

public class EditMerchandiserModel(){
        private MultipartFile file;

        //getters and setters for all the properties
}

The code in the controller that handles the file upload looks like the following

    if(model.getFile().isEmpty())  -->THROWING NULLPOINTER EXCEPTION HERE
    {
        MultipartFile file = model.getFile();
        String fileName = file.getOriginalFilename();
        String filePath = "/usr/local/" + fileName;
        FileOutputStream fos = new FileOutputStream(filePath);
         try 
             {

            fos.write(file.getBytes());
         } catch (IllegalStateException e) {
            System.out.println(e);

         }
         finally{
             fos.close();
         }
    }

I am unable to hit the inside code because it is reading in the file as a null value. Why is it not binding the value to the field?

+2  A: 

It looks like your file input box has the name "file" while the property it's supposed to bind to has the name "photo" (at least you're trying to retrieve it using "getPhoto()". Spring is smart, but it ain't that smart. :)

JacobM
Haha...good catch, the story is actually that it was originally called photo, but I changed it to file in order to make it generic for this post, but Thank you, I am going to make the edit for it...thanks alot
CitadelCSAlum
Hey I found what the problem is haha...It was a dependency innjection problem, but on top of that I made a mistake once it I fixed this... you will notice it says if(model.getFile().isEmpty()) instead of checking if it is not empty. Thanks for your help!
CitadelCSAlum