Spring文件混合上传


问题内容

我想将文件上传到我的spring 3.0 applicatoin(用roo创建)。

我已经有以下实体:

@Entity
@RooJavaBean
@RooToString
@RooEntity
public class SelniumFile {

    @ManyToOne(targetEntity = ShowCase.class)
    @JoinColumn
    private ShowCase showcase;

    @Lob
    @Basic(fetch = FetchType.LAZY)
    private byte[] file;

    @NotNull
    private String name;
}

但是我不确定如何在视图/控制器端实现它。我可以自由地将spring形式的标签<form:input>与常规标签混合<input type=file ...>吗?

我在MVC文档中看到了不错的分段上传部分,但仍需要一点帮助将其应用于我的特定情况。


问题答案:

更新:我认为我的问题表达得不好。我想做的是创造一个spring

我在较早的spring文档中找到了关于如何执行此操作的很好的解释,并将其应用于新的Spring 3.0
MVC。基本上,这意味着您需要在控制器的@InitBinder方法中注册PropertyEditor。之后,一切都会按预期进行(前提是您已将MultiPartResolver添加到上下文中并设置了正确的表单编码)。这是我的样本:

@RequestMapping("/scriptfile/**")
@Controller
public class ScriptFileController {

    //we need a special property-editor that knows how to bind the data
    //from the request to a byte[]
    @InitBinder
    public void initBinder(WebDataBinder binder)
    {
        binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
    }

    @RequestMapping(value = "/scriptfile", method = RequestMethod.POST)    
    public String create(@Valid ScriptFile scriptFile, BindingResult result, ModelMap modelMap) {    
        if (scriptFile == null) throw new IllegalArgumentException("A scriptFile is required");        
        if (result.hasErrors()) {        
            modelMap.addAttribute("scriptFile", scriptFile);            
            modelMap.addAttribute("showcases", ShowCase.findAllShowCases());            
            return "scriptfile/create";            
        }        
        scriptFile.persist();        
        return "redirect:/scriptfile/" + scriptFile.getId();        
    }    
}