使用 Spring 和 Hibernate 将用户选择的图像上传到数据库中

Uploading an image selected by the user into the database with Spring and Hibernate

请耐心等待,因为我几个月前才学会编码。我无法将用户选择的图像上传到数据库中。我能够上传硬编码图像(例如 "C:\imageName.jpg")。

我的jsp代码:

<form:input path="pic" type="file" class="btn" name="image" enctype="multipart/form-data" />

编辑

谢谢 M. Deinum,在阅读了您发布的 link 之后,我添加了这个 bean:

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

</bean>

我的控制器现在有这个代码:

RequestMapping 现在包含:headers = "content-type=multipart/*" 附加参数:MultipartHttpServletRequest request

@RequestParam(value="image", defaultValue="") MultipartFile file

byte[] bytes = null;
if (!file.isEmpty()) {
                bytes = file.getBytes();
                InputStream inputStream = file.getInputStream();
                inputStream.read(bytes);
                inputStream.close();
            }

我的新错误代码:

The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.

进一步编辑

对于任何感兴趣的人,这是我的控制器的完整代码:

@RequestMapping(value="/processsettings", method = RequestMethod.POST, headers = "content-type=multipart/*")
public String processSettings(@ModelAttribute("changeUser") User changeUser, BindingResult result, HttpSession session, Model model, HttpServletResponse response, MultipartHttpServletRequest request,
@RequestParam(value="image", defaultValue="") MultipartFile file) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {

    byte[] bytes = null;

    if (!file.isEmpty()){
        bytes = file.getBytes();
        InputStream inputStream = file.getInputStream();
        inputStream.read(bytes);
        inputStream.close();
    }
    changeUser.setPic(bytes);
    userService.updateUser(changeUser);
    session.setAttribute("currentUser", changeUser);

    return "Settings";
}

为了像我这样的其他初学者的利益,我们就是这样解决的。我的原始代码实际上更正确。

RequestParam 应该是:

@RequestMapping(value="/processsettings", method = RequestMethod.POST)
public String processSettings(@ModelAttribute("changeUser") User changeUser, BindingResult result, HttpSession session, Model model, HttpServletResponse response,     
@RequestParam(value="pic", defaultValue="") CommonsMultipartFile pic

代码很简单:

if (!pic.isEmpty()) {
    byte[] imageByte = pic.getBytes();
    changeUser.setPic(imageByte);
}

要包含的重要 jar:

commons-io-2.4.jar