在spring mvc中将文件名传递给控制器

时间:2014-08-06 04:17:47

标签: java spring spring-mvc

我允许用户上传xls文件。 单击按钮我想将文件名传递给控制器​​,并希望读取文件内容。

这是jsp代码:

function uploadTemplate()
    {
        //window.location.href = "uploaduserdashboardreqmultiple";  
        String fileName = document.getElementById("filename").value;
        document.uploadRequest.action = "uploadFile?filename"+filename;
        document.uploadRequest.submit();
    }


<form:form action="" method="POST" modelAttribute="uploadFile" name="uploadRequest"  enctype="multipart/form-data">     
                    <div align="center" style="margin-bottom: 10px;">
                        <button onClick = "downloadTemplate()"  style="width:250px" type="submit" class="admin_search_btn"><spring:message code="lblDownloadXls"></spring:message></button>
                    </div>
                    <div align="center" style="margin-bottom: 10px;" >                  
                        <form:input path="fileName" style="width:200px" id="filename" class="admin_search_btn" type="file" />
                         <div align="center" style="margin-bottom: 10px;" > 
                            <button onClick = "uploadTemplate()" type="submit" class="admin_search_btn"><spring:message code="lblSubmit"></spring:message></button>&nbsp;
                            <button  type="submit" class="admin_search_btn">Cancel</button>
                        </div>          
                    </div>                      
                </form:form>        

点击按钮,我调用了函数并将文件名传递给控制器​​。

控制器:

@RequestMapping(value = "/uploadFile")
public 
String uploadFileHandler(@ModelAttribute UploadFile uploadFile,
        @RequestParam("filename") String name
      /*  @RequestParam("file") MultipartFile file*/) {

    if (!name.isEmpty()) {
        try {
            byte[] bytes = name.getBytes();

            // Creating the directory to store file
            String rootPath = System.getProperty("catalina.home");
            File dir = new File(rootPath + File.separator + "tmpFiles");
            if (!dir.exists())
                dir.mkdirs();

            // Create the file on server
            File serverFile = new File(dir.getAbsolutePath()
                    + File.separator + name);
            BufferedOutputStream stream = new BufferedOutputStream(
                    new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();             

            return "You successfully uploaded file=" + name;
        } catch (Exception e) {
            return "You failed to upload " + name + " => " + e.getMessage();
        }
    } else {
        return "You failed to upload " + name
                + " because the file was empty.";
    }
}

我没有收到任何错误。但是当我检查调试模式时,它会显示nulluploadFile的{​​{1}}

我做错了吗?

2 个答案:

答案 0 :(得分:2)

您可以尝试使用MultipartFile#getOriginalFilename()

模型/命令类

private CommonsMultipartFile imageFile;

JSP / HTML:

<%@taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<sf:input path="imageFile" type="file" />

查看完整的Example1Example2


根据您的上一条评论,请尝试

以下代码来自spring in action 3rd edition - chapter 7

我有一个示例项目,用于在服务器上传图像。它只是我示例项目的registration页面的一部分。

JSP:

<%@taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<sf:form method="POST" modelAttribute="spitter"
    enctype="multipart/form-data">
    <sf:input path="imageFile" type="file" />
</sf:form>

控制器:

// first request
@RequestMapping("/signup")
public String showSpitterForm(Model model) {
    model.addAttribute("spitter", new SpitterModel());
    return "signup";
}

/*
 * Form submission for spitter registration
 */
@RequestMapping(value = "/signup", method = RequestMethod.POST)
public String addSpitterFromForm(
        @Valid @ModelAttribute("spitter") SpitterModel spitterModel,
        BindingResult bindingResult, HttpSession session,
        HttpServletRequest request) {
    if (bindingResult.hasErrors()) {
        return "signup";
    }  else {
        saveSpitter(spitterModel, session
                .getServletContext().getRealPath("/resources/upload"));
        return "redirect:list";
    }
}

SpitterModel:

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

public class SpitterModel  {

    private CommonsMultipartFile imageFile;

    public CommonsMultipartFile getImageFile() {
        return imageFile;
    }

    public void setImageFile(CommonsMultipartFile imageFile) {
        this.imageFile = imageFile;
    }

}

方法saveSpitter

MultipartFile file = model.getImageFile();
inputStream = file.getInputStream();
outputStream = new FileOutputStream(fullyFileName);

int readBytes = 0;
byte[] buffer = new byte[1024 * 50];
while ((readBytes = inputStream.read(buffer, 0, 1024 * 50)) != -1) {
    outputStream.write(buffer, 0, readBytes);
}

spring配置文件:

<!-- Configure the multipart resolver -->
<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />

答案 1 :(得分:1)

我认为您缺少在servlet-context.xml文件中添加multipartResolver bean -

<!-- Multipart Resolver -->
<beans:bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <beans:property name="maxUploadSize" value="5000000" />
        <!-- Max size in bytes. -->
    <beans:property name="maxInMemorySize" value="4096" />
    <!-- Max size in memory. -->
</beans:bean>

并在pom.xml中添加给定的依赖项

    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.2.2</version>
    </dependency>

而不是调用uploadTemplate()函数将表单标签中的提交按钮设置操作属性设置为uploadFile,如下所示 -

<form:form action="uploadFile" method="POST" modelAttribute="uploadFile" name="uploadRequest"  enctype="multipart/form-data">