0

I have a jsp page in which i have used spring form tag so that i can use model attribute and bind data to it. It was working fine on submit the form but after adding enctype="multipart/form-data" model attributes are returing null to the controller. What is wrong here ? My Code is - proflie.jsp

 <sf:form method="POST" action="update" modelAttribute="user" class="form-horizontal" >
    <div class="form-group">
        <label for="inputEmail3" class="col-sm-2 control-label">Avatar</label>
        <div class="col-md-6">
            <div class="media v-middle">
                <div class="media-left">
                    <div class="icon-block width-100 bg-grey-100">
                        <i class="fa fa-photo text-light"></i>
                    </div>
                </div>
                <div class="media-body">
                    <i class="fa fa-upl"><sf:input path="imageFile" type="file" class="btn btn-white btn-sm paper-shadow relative" placeholder="Add Image" id="imageFile" />
                     </i>
                </div>
            </div>
        </div>
    </div>
    <div class="form-group">
        <label for="inputEmail3" class="col-md-2 control-label">Full Name</label>
        <div class="col-md-8">
            <div class="row">
                <div class="col-md-6">
                    <div class="form-control-material">
                        <sf:input path="firstName" type="text" class="form-control" id="firstName" placeholder="Your first name" value="${user.firstName}" />
                        <sf:input path="id" type="hidden" class="form-control" id="id" value="${user.id}" />
                        <label for="firstName">First name</label>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-control-material">
                            <sf:input path="lastName" class="form-control" id="lastName" placeholder="Your last name" value="${user.lastName}" />
                        <label for="lastName">Last name</label>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="form-group">
        <label for="inputEmail3" class="col-md-2 control-label">Email</label>
        <div class="col-md-6">
            <div class="form-control-material">
                <div class="input-group">
                    <span class="input-group-addon"><i class="fa fa-envelope"></i></span>
                    <sf:input path="email" type="email" class="form-control" id="inputEmail3" placeholder="Email" value="${user.email}" />
                    <label for="inputEmail3">Email address</label>
                </div>
            </div>
        </div>
    </div>
     <div class="form-group">
        <label for="inputEmail3" class="col-md-2 control-label">Phone</label>
        <div class="col-md-6">
            <div class="form-control-material">
                <div class="input-group">
                    <span class="input-group-addon"><i class="fa fa-envelope"></i></span>
                    <sf:input path="phone" type="number" class="form-control" id="inputEmail3" placeholder="Phone" value="${user.phone}" />
                    <label for="phone">Phone</label>
                </div>
            </div>
        </div>
    </div>
    <div class="form-group">
        <label for="inputEmail3" class="col-md-2 control-label">Address</label>
        <div class="col-md-6">
            <div class="form-control-material">
                <div class="input-group">
                    <span class="input-group-addon"><i class="fa fa-link"></i></span>
                    <sf:input path="address" type="text" class="form-control used" id="website" placeholder="Address" value="${user.address}" />
                    <label for="address">Address</label>
                </div>
            </div>
        </div>
    </div>
    <div class="form-group">
        <label for="inputPassword3" class="col-md-2 control-label">Change Password</label>
        <div class="col-md-6">
            <div class="form-control-material">
               <sf:input path="password" type="password" class="form-control" id="inputPassword3" placeholder="Password" value="${user.password}" />
                <label for="password">Password</label>
            </div>
        </div>
    </div>

    <div class="form-group margin-none">
        <div class="col-md-offset-2 col-md-10">
            <button type="submit" class="btn btn-primary paper-shadow relative" data-z="0.5" data-hover-z="1" data-animated>Save Changes</button>
        </div>
    </div>
</sf:form>

AccountController class

package com.vc.teacher.controller;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.vc.teacher.db.dao.UserDao;
import com.vc.teacher.entities.User;
import com.vc.teacher.util.Constants;

@Controller
public class AccountController {

    @Autowired
    UserDao userDao;

    @RequestMapping("/login")
    public String loginUser(@RequestParam("email") String email,
            @RequestParam("password") String password, Model model) {

        User user = userDao.checkCreditionals(email, password);
        if (user != null) {
            model.addAttribute("user", user);
            return "jsp/profile";
        } else {
            model.addAttribute("error", "Wrong creditionals");
            return "jsp/signin";
        }

    }

    @RequestMapping("/signUp")
    public String initilize(Model model) {
        model.addAttribute(new User());
        return "jsp/signup";
    }

    @RequestMapping(method = RequestMethod.POST, value = "/register")
    public String signUpUser(User user, RedirectAttributes attributes) {
        boolean result = false;
        File imageFile = null;

        try {
            imageFile = user.getImageFile();

            if (imageFile != null) {
                File imageFileSave = new File(Constants.MEDIA_FILE_PATH);
                FileUtils.copyFile(imageFile, imageFileSave);
                user.setImageFileName(imageFile.getName());
            }

            user.setStatus("Deactive");
            result = userDao.registerUser(user);

            if (result == true) {
                attributes.addFlashAttribute("message",
                        "You are ready to go now !");
                return "redirect:/signUp";
            } else {
                attributes.addFlashAttribute("message", "Something went wrong");
                return "redirect:/signUp";
            }

        } catch (Exception e) {
            attributes.addFlashAttribute("message", "Something went wrong");
            return "redirect:/signUp";
        }

    }

    @RequestMapping(method = RequestMethod.POST, value = "/update")
    public String updateUser(User user, RedirectAttributes attributes) {
        boolean result = false;
        File imageFile = null;

        try {
            System.out.println("=================================="+user.getEmail());
            System.out.println("=================================="+user.getId());
            System.out.println("=================================="+user.getFirstName());

            imageFile = user.getImageFile();

            if (imageFile != null) {
                File imageFileSave = new File(Constants.MEDIA_FILE_PATH);
                FileUtils.copyFile(imageFile, imageFileSave);
                user.setImageFileName(imageFile.getName());
            }

            user.setStatus("Active");
            result = userDao.updateUser(user);

            if (result == true) {
                attributes.addFlashAttribute("message", "Profile Updated !");
                return "jsp/profile";
            } else {
                attributes.addFlashAttribute("message", "Something went wrong");
                return "jsp/profile";
            }
        } catch (Exception e) {
            attributes.addFlashAttribute("message", "Something went wrong");
            return "jsp/profile";
        }

    }
}

1 Answer 1

3

On its own, DispatcherServlet doesn't know how to handle multipart form data; that's why we require multipart resolver.

You should register it in your servlet-config:

    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="500000" />
    </bean>

Use CommonsMultipartFile or MultipartFile instead of File in your User object:

private CommonsMultipartFile imageFile;

You can try this code to save file:

File imageFileSave = new File(Constants.MEDIA_FILE_PATH);
FileUtils.writeByteArrayToFile(imageFileSave , imageFile.getBytes());
Sign up to request clarification or add additional context in comments.

5 Comments

It is giving this exception - Cannot convert value of type [org.springframework.web.multipart.commons.CommonsMultipartFile] to required type [java.io.File] for property 'imageFile': PropertyEditor [org.springframework.beans.propertyeditors.FileEditor] returned inappropriate value of type [org.springframework.web.multipart.commons.CommonsMultipartFile]]
Why i can use File in my user object.
@Admit Das i think u cant use java.io.File, but u probably can do everything you need with MultipartFile. I gave you example how to save file for example
I got it that. But i am asking about the reason behind it that why i cant use java.io.File
@Admit Das Maybe because File is an abstract representation of file and directory pathnames. Check here: stackoverflow.com/questions/17595091/…. I think you should make another question if u want more info, because its a bit off topic here.

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.