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



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

我的 jsp 代码:

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

编辑

谢谢 M. Deinum,在阅读了您发布的链接后,我添加了这个豆子:

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

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

请求参数应为:

@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);
}

要包括的重要罐子:

共享资源-IO-2.4.jar

最新更新