文件上传控制器servlet未收到请求

时间:2014-11-16 20:19:20

标签: java spring spring-mvc java-ee servlets

我是Spring MVC的新手。

我正在尝试通过我的网站为我的项目创建文件上传。我正在使用此example

/**
 * Upload single file using Spring Controller
 */
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public @ResponseBody
String uploadFileHandler(@RequestParam("fileN") MultipartFile file) {

    if (!file.isEmpty()) {
        try {
            byte[] bytes = file.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();

            logger.info("Server File Location="
                    + serverFile.getAbsolutePath());

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

但是无论如何,上面的控制器servlet都不会收到Web请求。 我的网站代码是一个简单的形式:

<form  id="uploadform" method="POST" enctype="multipart/form-data" action="uploadFile">

<table width="100%">
<tr><td style="width: 17%; height:450px; background: #007dc6" valign="top">
<a href="LandingPage.ftl" style="position: relative; top: 40px; left: 20px; font-size: 15pt; font-weight: BOLD; color: yellow;">Home</a>
<br/>
<a href="bussLandingPage.ftl" style="position: relative; top: 40px; left: 20px; font-size: 14pt; font-weight: BOLD; color: yellow;">Back</a>
<a href="${rc.contextPath}/logout" style="position: relative; top: 40px; left: 20px; font-size: 15pt; font-weight: BOLD; color: yellow;">Logout</a>
</td>

<td align="center" style="background:#e6e6e6">

<div id="mainSection" >


Template download link: <button id="download">Download Template</button>
<br/>
<br/>
Upload new DC setup request: <input type="file" id="fileN"></input>

<button id="submit">Submit</button>

<p color="red">${error}</p>

</div>


</td>
</tr>
</table>


</form>

如果我将上述控制器servlet修改为以下类型,我会收到我的网络请求

@RequestMapping(value = "/uploadFile" , method = RequestMethod.POST)
    public @ResponseBody
    String uploadFileHandler(HttpServletRequest req) {

为什么第一个代码不能用于我的项目?有什么不同?如果您需要任何其他信息,我将很乐意提供。

由于

1 个答案:

答案 0 :(得分:0)

似乎问题出现在HTML中:

<input type="file" id="fileN"></input>

this post所述:&#34;只有具有name属性的标签才会发送到服务器&#34;。

替换为:

<input type="file" id="fileN" name="fileN"/>