【发布时间】:2015-01-13 17:02:48
【问题描述】:
我是 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无论如何都没有收到网络请求。 我的网站代码是一个简单的形式,即:
<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 修改为以下类型,我会收到我的 web 请求
@RequestMapping(value = "/uploadFile" , method = RequestMethod.POST)
public @ResponseBody
String uploadFileHandler(HttpServletRequest req) {
为什么第一个代码不适用于我的项目?有什么区别?如果您需要任何其他信息,我很乐意提供。
谢谢
【问题讨论】:
标签: java spring spring-mvc jakarta-ee servlets