Spring多文件上传表单验证

5

我对Spring框架不熟悉,目前在处理多部分表单提交/验证场景时遇到了很多问题,特别是在视图中显示错误信息方面。

这是我目前拥有的文件:

resourceupload.jsp:一个显示上传文件表单的视图。

<form:form method="post" action="resource/upload" enctype="mutlipart/form-data">
 <input name="name" type="text"/>
 <input name="file" type="file" />
 <input type="submit"/>
<form:errors path="file" cssClass="errors"/>
</form>

resourceuploadcontroller.java:处理表单提交的控制器,并(不成功地)尝试将文件验证错误返回到视图:

@RequestMapping(method = RequestMethod.POST)
public String handleFormUpload( @RequestParam("file") MultipartFile file , @RequestParam("name") String name,Object command, Errors validationErrors){
..perform some stuff with the file content, checking things in the database, etc...
.. calling validationErrors.reject("file","the error") everytime something goes wrong...

return "redirect:upload"; // redirect to the form, that should display the error messages

很明显,这种方法存在问题:

1/ 我不得不在validationErrors参数之前添加一个虚拟的“command”对象,否则Spring会抛出错误。这似乎并不正确。

2/ 在我添加了该参数后,重定向没有将错误传递到视图。我尝试在控制器开头使用@SessionAttribute("file"),但没有任何运气。

如果有人能够帮忙...我看了一下@ResponseBody注释,但那似乎不是用于视图的。

4个回答

3

看起来我自己找到了解决方案。

首先是很有帮助的链接:http://www.ioncannon.net/programming/975/spring-3-file-upload-example/Spring 3 MVC - form:errors not showing the errors 其中提供了一个不错的技巧,可以显示所有错误,使用

<form:errors path="*"/>. 

现在,这是我所做的所有更改列表,以使该事项起作用:
1/ 使用“rejectValue”而不是“reject”。
2/ 直接返回视图而不是重定向。
3/ 创建一个具有CommonsMultipartFile属性的“UploadItem”模型。
总的来说,我的控制器方法变成了:
@RequestMapping(method = RequestMethod.POST)
public String handleFormUpload( @ModelAttribute("uploadItem") UploadItem uploadItem, BindingResult errors){
... use errors.rejectValue ... in case of errors (moving everything i could in a UploadItemValidator.validate function)
return "uploadform"

希望能对您有所帮助。

3

以下是一种非常简单的方法:

formBackingObject:

import org.springframework.web.multipart.commons.CommonsMultipartFile;

public class FileImport {

    CommonsMultipartFile  importFile;

    public CommonsMultipartFile getImportFile() {
        return importFile;
    }

    public void setImportFile(CommonsMultipartFile importFile) {
        this.importFile = importFile;
    }
}

表单:
<sf:form method="POST" modelAttribute="fileImport" enctype="multipart/form-data" action="import">
    <table>
        <spring:hasBindErrors name="fileImport">
            <tr>
                <td colspan="2">
                    <sf:errors path="importFile" cssClass="error"/>
                </td>
            </tr>
        </spring:hasBindErrors>
        <tr>
            <th><label for="importFile">Import Workload:</label></th>
            <td><input name="importFile" type="file"></td>
        </tr>
    </table>
    <input type="submit" value="Import Application Data">
</sf:form>

最后是ControllerClassMethod:

@RequestMapping(value={"/import"}, method=RequestMethod.POST)
public String importWorkload(
        FileImport fileImport, BindingResult bindResult,
        @RequestParam(value="importFile", required=true) MultipartFile importFile ){
    if( 0 == importFile.getSize() ){
        bindResult.rejectValue("importFile","fileImport.importFile");
    }

    if(bindResult.hasErrors()){
        return "admin";
    }
....
}

简单易懂!

@NotNull注释不能用于文件,因为在请求对象中,multipart文件从来不是null。但它可能含有0字节。您可以花时间实现自定义验证器,但为什么呢?


2
在Spring 4中,您可以按照以下方式实现文件验证器:
@Component
public class FileValidator implements Validator {

    @Override
    public boolean supports(Class<?> clazz) {
        return FileModel.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        FileModel fileModel = (FileModel) target;

        if (fileModel.getFile() != null && fileModel.getFile().isEmpty()){
            errors.rejectValue("file", "file.empty");
        }
    }
}

然后将以上的验证器注入到上传控制器中,代码如下:

@Controller
@RequestMapping("/")
public class FileUploadController {

    @Autowired
    private FileValidator fileValidator;

    @ModelAttribute
    public FileModel fileModel(){
        return new FileModel();
    }

    @InitBinder
    protected void initBinderFileModel(WebDataBinder binder) {
        binder.setValidator(fileValidator);
    }

    @RequestMapping(method = RequestMethod.GET)
    public String single(){
        return "index";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String handleFormUpload(@Valid FileModel fileModel,
                                   BindingResult result,
                                   RedirectAttributes redirectMap) throws IOException {

        if (result.hasErrors()){
            return "index";
        }

        MultipartFile file = fileModel.getFile();
        InputStream in = file.getInputStream();
        File destination = new File("/tmp/" + file.getOriginalFilename());
        FileUtils.copyInputStreamToFile(in, destination);

        redirectMap.addFlashAttribute("filename", file.getOriginalFilename());
        return "redirect:success";
    }
}

这个实现可以使你的代码更加清晰易读。我是从Spring MVC文件上传验证示例教程中发现了它。


1

我认为这种方法并没有完全采用Spring,但它是有效的、简单的,并使用了一个简单的HTML表单和控制器中的一个方法:

HTML文件用于进行POST操作(保存为JSP或HTML,由您决定)。

<html>
  <head>
    <title>File Upload Example</title>
  </head>
  <body>
    <form action="save_uploaded_file.html" method="post" enctype="multipart/form-data">
        Choose a file to upload to the server:
        <input name="myFile" type="file"/><br/>
      <p>
        <input type="submit"/>
        <input type="reset"/>
      </p>
    </form>
  </body>
</html>

在你的控制器中,添加以下方法:
@RequestMapping("/save_uploaded_file")
public String testUpload(HttpServletRequest request) throws Exception
{
    // get the file from the request
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile multipartFile = multipartRequest.getFile("myFile");

    // Note: Make sure this output folder already exists!
    // The following saves the file to a folder on your hard drive.
    String outputFilename = "/tmp/uploaded_files/file2.txt";
    OutputStream out = new FileOutputStream(outputFilename);
    IOUtils.copy(multipartFile.getInputStream(), out);

    return "/save_uploaded_file";
}

为了使大于40k的文件可以上传,您可能需要在Spring Servlet配置中指定以下内容...我已经放置了一些大数字以确保它能够正常工作,但如果需要,请使用“真实”数字。
<!-- Configure the multipart resolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- one of the properties available; the maximum file size in bytes -->
    <property name="maxUploadSize" value="500000000"/>
    <property name="maxInMemorySize" value="500000000" />
</bean>

请注意,Spring的文件上传功能在底层使用Apache Commons FileUpload。您需要下载并将其包含在您的应用程序中。这又需要Apache Commons IO,因此您也需要它。(引自这里)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接