java - Spring文件以混合形式上传

标签 java spring file-upload spring-mvc

我想将文件上传到我的 spring 3.0 应用程序(使用 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;
}

但我不确定如何在 View / Controller 端实现它。我可以自由混合 Spring 形式的标签,如 <form:input>带有普通标签,如 <input type=file ...> ?

我见过漂亮的multipart upload section在 MVC 文档中,但仍需要一些帮助才能将其应用于我的具体案例。

最佳答案

更新:我认为我的问题表述不当。我想做的是创造一个 Spring

我在旧的 spring 文档中找到了一个很好的解释,并将其应用于新的 Spring 3.0 MVC。基本上这意味着您需要在 Controller 的@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();        
    }    
}

关于java - Spring文件以混合形式上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2190851/

相关文章:

php - 如何用 PHP 上传一个 .txt 文件并在另一页上逐行读取它?

java - 告诉 Hibernate 仅让数据库在值为 null 时生成值

java - "Verify EAR Libraries"链接资源错误

java - Eclipselink、c3p0 和 Spring - 创建太多连接!

java - Spring Integration - 跨步骤共享锁

jsf - <p :fileUpload> recreates @ViewScoped bean on every request

java - oracle11g 和 JDBC 中的自动增量

java - 使用 guice 将运行时参数传递给构造函数

java - 仅在使用基于 Spring java 的配置运行测试时初始化数据库

c# - 如何使用 C# 将数据插入 SQL 表并实现上传功能?