【问题标题】:File uploading not working in spring mvc using spring form使用spring表单在spring mvc中文件上传不起作用
【发布时间】:2015-08-21 06:56:41
【问题描述】:

我有一个 jsp 页面,其中我使用了 spring 表单标签,以便我可以使用模型属性并将数据绑定到它。它在提交表单时工作正常,但在添加 enctype="multipart/form-data" 模型属性后将 null 返回到控制器。这里有什么问题? 我的代码是 - 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 类

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";
        }

    }
}

【问题讨论】:

    标签: java spring spring-mvc


    【解决方案1】:

    DispatcherServlet 本身不知道如何处理多部分表单数据;这就是我们需要多部分解析器的原因。

    你应该在你的 servlet-config 中注册它:

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

    在您的用户对象中使用 CommonsMultipartFile 或 MultipartFile 而不是 File:

    private CommonsMultipartFile imageFile;
    

    你可以试试这个代码来保存文件:

    File imageFileSave = new File(Constants.MEDIA_FILE_PATH);
    FileUtils.writeByteArrayToFile(imageFileSave , imageFile.getBytes());
    

    【讨论】:

    • 它给出了这个异常 - 无法将类型 [org.springframework.web.multipart.commons.CommonsMultipartFile] 的值转换为属性“imageFile”所需的类型 [java.io.File]:PropertyEditor [ org.springframework.beans.propertyeditors.FileEditor] 返回了不合适的类型值 [org.springframework.web.multipart.commons.CommonsMultipartFile]]
    • 为什么我可以在我的用户对象中使用 File。
    • @Admit Das 我认为您不能使用 java.io.File,但您可能可以使用 MultipartFile 完成您需要的一切。我举了一个例子,例如如何保存文件
    • 我明白了。但我在问为什么我不能使用 java.io.File 背后的原因
    • @Admit Das 也许是因为 File 是文件和目录路径名的抽象表示。在这里查看:stackoverflow.com/questions/17595091/…。如果你想了解更多信息,我认为你应该提出另一个问题,因为这里有点离题了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多