java - Spring 中未选择文件提交表单失败

标签 java jsp spring-mvc

我希望我的表单可以提交带有其他公共(public)字段的图片,但是我发现如果我在表单中选择图片,提交会成功,但如果我不选择图片,提交会抛出400错误:

Type Status Report

Message Required request part 'profilePicture' is not present

Description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).


Apache Tomcat/8.5.23    

查看我的jsp代码:

<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form"  %>
<sf:form method="POST" modelAttribute="spitter" enctype="multipart/form-data">
<sf:errors path="*" cssClass="error" element="div"></sf:errors><br/>
<sf:label path="id" cssErrorClass="error">User ID:</sf:label> <sf:input  path="id" cssErrorClass="error" /><sf:errors path="id" />   <br />
<sf:label path="firstName" cssErrorClass="error">First Name: </sf:label><sf:input  path="firstName" cssErrorClass="error"/><sf:errors path="firstName" cssClass="error" />  <br/>
<sf:label path="lastName" cssErrorClass="error">Last Name: </sf:label><sf:input  path="lastName" cssErrorClass="error"/><sf:errors path="lastName" cssClass="error"/> <br/>
<sf:label path="password" cssErrorClass="error">Password: </sf:label><sf:password  path="password" cssErrorClass="error"/><sf:errors path="password" cssClass="error"/> <br/>
<br />
<label>Profile Picture</label>
<input type="file" name="profilePicture" 
       accept="image/jpeg,image/png,image/gif" /><br />
<input type="submit" value="Register" />
</sf:form>

这是我的 Controller 方法:

@RequestMapping(value="/register", method=RequestMethod.POST)
public String processRegistration(
        @RequestPart("profilePicture") byte[] profilePicture,
        @Valid Spitter spitter, Errors errors)
{
    System.out.println("SpitterController.processRegistration is called first time");
    if (errors.hasErrors())
    {
        System.out.println("find errors");
        return "registerForm";
    }
    System.out.println("SpitterController.processRegistration is called");
    System.out.println(spitter.toString());
    spitterRespository.saveSpitter(spitter);

    return "redirect:/spitter/"+spitter.getId();
}

我不知道如何解决这个问题,也不知道原因,有人可以帮助我吗?

最佳答案

@RequestPart(name = "profilePicture", required = false) byte[] profilePicture,

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestPart.html

关于java - Spring 中未选择文件提交表单失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47521778/

相关文章:

javascript - JSP getParameter 和 JQuery GET ajax 有问题

java - 如何在 Spring MVC 中将未编码的字符串写入 View ?

java - 在 Struts2 中使用 AJAX 根据另一个选择菜单填充一个选择菜单

java - 如何在 JSP/JSTL 中对 URL 进行 URL 编码?

java - 在一个类中收集多个查询参数

java - 拒绝在 spring security 中具有相同角色的多个用户访问

java - 限制 REST API 的 JSON 响应中的字段?

java - 错误: Could not find or load main class while executing jar file

java - 如何使用套接字 channel 通过网络发送图像文件

java - Jackson双向嵌套对象设置