2014-11-16 2 views
0

Я новичок в 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."; 
    } 
} 

Но сервлет-контроллер выше не получает веб-запрос независимо от того, что. Мой сайт код представляет собой простую форму, которая является:

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

Если я изменить выше контроллер сервлет это ниже типа я получу свой веб-запрос

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

Почему не первый код работает для мой проект? в чем разница? Если вам нужна какая-либо другая информация, я буду рад предоставить ее.

Благодаря

ответ

0

Казаться проблема в HTML:

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

Как написано в this post: «только теги с атрибутом имени посылаются на сервер».

Заменить трейлеры:

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

Вау, удивительный, что работал как шарм !! Большое спасибо за помощь. Но почему только теги с атрибутом имени отправляются на сервер? В чем смысл? –

+0

Работает по спецификации HTML: http://www.w3.org/TR/html401/interact/forms.html#h-17.2 – ursa

Смежные вопросы