java - 在 spring mvc 中将文件名传递给 Controller

标签 java spring spring-mvc

我允许用户上传 xls 文件。 单击按钮我想将文件名传递给 Controller ​​并想读取文件内容。

这是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>        

单击按钮时,我已调用函数并将文件名传递给 Controller ​​。

Controller :

@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.";
    }
}

我没有收到任何错误。但是当我在 Debug模式下检查时,它为 uploadFilefilename

显示 null

我做错了什么吗?

最佳答案

你可以试试MultipartFile#getOriginalFilename()

模型/命令类

private CommonsMultipartFile imageFile;

JSP/HTML:

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

看看完整的Example1Example2


根据你最后的评论,试试<​​/p>

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

我有用于在服务器上载图像的示例项目。它只是我示例项目的注册页面的一部分。

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>

Controller :

// 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;
    }

}

方法保存Spitter

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" />

关于java - 在 spring mvc 中将文件名传递给 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25152152/

相关文章:

java - Spring Data REST、QueryDSL 和 HashMaps - 引用 HashMap 属性时来自 URL 的 Null 谓词

java - Stripes 1.6 缺少 Spring Interceptor

java - 我应该将我的业务不变检查放入 Controller 中吗

多帐户 Web 应用程序中的 Java Spring 身份验证、授权和所有权

java - Spring批处理从2.1.8.RELEASE升级到3.0.0.RELEASE抛出异常

java - 使用 Spring EL 将值设置为 lambda

Spring MVC 在 intellij idea 10 中不起作用

javascript - angularjs 应用程序中的 HTML 5 url

java - Java 中的余弦相似性性能比等效的 C 慢 15 倍?

java - Spring @Value 连接指向 JSON 文件的 Resource 实例