这是一个示例,展示了如何使用 MVC Annotations 在 Spring 中实现类似的功能:
@RequestMapping(method=RequestMethod.POST, value="/multipartexample")
public String examplePost(@ModelAttribute("fileUpload") FileUpload fileUpload){
// Handle form upload and return a view
// ...
}
@InitBinder
public void initBinder(ServletRequestDataBinder binder) {
binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
}
public class FileUpload implements Serializable {
private MultipartFile myFile;
public MultipartFile getMyFile() {
return myFile;
}
public void setMyFile(MultipartFile myFile) {
this.myFile = myFile;
}
}
假设文件元素的名称是“myFile”,您应该能够从 html 表单发布到此端点。您的表单可能如下所示:
<form:form commandName="fileUpload" id="fileUploadForm" enctype="multipart/form-data">
<form:input type="file" path="myFile" id="myFile"/>
</form:form>
@InitBinder 代码很重要,因为它指示 Spring 将文件转换为字节数组,然后可以将其转换为 MultipartFile