如何在spring中绑定文件并在文件夹中上传文件

时间:2016-12-25 12:57:25

标签: java spring-mvc file-upload

我在spring中绑定文件时遇到问题。我试图将文件保存在文件夹中并将文件名保存在数据库中。但是我在表单中绑定文件时遇到了一些错误。

@Controller

@RequestMapping(value="/addStudent",method=RequestMethod.POST)
public String saveStudent(@RequestParam("images") MultipartFile files,@ModelAttribute("addstd") StudentInfo theStudent,Model model){
      String fileName=null; 

    if(!files.isEmpty()){

        try {
            String path= session.getServletContext().getRealPath("/WEB-INF/resources/images");
            String newName=String.valueOf(new java.util.Date().getTime());
            fileName=files.getOriginalFilename();
            String ext=FilenameUtils.getExtension(fileName);
            File imageFile=new File(path,newName+"."+ext);
            files.transferTo(imageFile);
            theStudent.setImages(newName+"."+ext);

        } catch (Exception e) {

        }
    }
    studentService.saveStudent(theStudent);
    return "redirect:/login";
}

数据库类

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id")
private int id;

@Column(name="year_id")
private int year;


@Column(name="faculty_id")
private int faculty;

@Column(name="firstname")
private String firstName;

@Column(name="lastname")
private String lastName;

@Column(name="contact_no")
private String contact_No;

@Column(name="address")
private String address;

@Column(name="email")
private String email;

@Column(name="images")
private String images;

我的jsp页面是:

    <form:form action="addStudent" enctype="multipart/form-data" modelAttribute="addstd" method="POST">    
    <form:hidden path="id" />
    <form:input path="firstName" placeholder="Fistname" />
    <form:input path="lastName" placeholder="Lastname" />
    <form:input path="contact_No" placeholder="Contact Number" />
    <form:input path="address" placeholder="Address" />
    <form:input path="email" placeholder="Email" /
    Year:

    <form:select path="year">
            <c:forEach var="temp" items="${studentyear}">
            <form:option value="${temp.yearId}">${temp.year}</form:option>
            </c:forEach>
        </form:select>   

      Faculty: 
        <form:select path="faculty">
            <c:forEach var="temp" items="${studentfaculty}">
            <form:option value="${temp.faculty_id}" >${temp.faculty}</form:option>
            </c:forEach>
        </form:select>
      Profile: <form:input type="file" path="images"  />

    <input type="submit" value="Add/Update Record" class="button" />
</form:form>

在此代码中,我收到错误“客户端发送的请求在语法上不正确。”

1 个答案:

答案 0 :(得分:0)

删除jsp

中以下代码段中的路径
<form:input type="file" path="images"  />

并替换为name =“images”

<input type="file" name="images"  />

因为路径会尝试使用pojo进行映射。