2011-03-09 78 views
2

的Servlet爪哇 - 文件上传问题

import java.io.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 
import java.util.Iterator; 
import java.util.List; 
import org.apache.commons.fileupload.servlet.ServletFileUpload; 
import org.apache.commons.fileupload.disk.DiskFileItemFactory; 
import org.apache.commons.fileupload.*; 

public class Apply extends HttpServlet 
{ 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
          throws ServletException, IOException 
    { 
     InputStreamReader input = new InputStreamReader(request.getInputStream()); 
     BufferedReader buffer = new BufferedReader(input); 
     String line=""; 
     line=buffer.readLine(); 

     System.out.println("Multipart data " + line); 

     boolean isMultipart = ServletFileUpload.isMultipartContent(request); 
     if(isMultipart) 
     { 
      // upload file 
     } 
     else 
     { 
      // failed, no input 
     } 
    } 

    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
          throws ServletException, IOException 
    { 
     doPost(request, response); 
    } 
} 

JSP。

 <form enctype="multipart/form-data" method="post" action="apply"> 
      <fieldset> 
       <br/> 
       <legend>Upload</legend> 
       <br/> 
       <label>Select file to upload</label> 
       <input type="file" name="file" /><br /> 
       <br/> 
       <a href="apply" class="jUiButton">Submit</a> 
      </fieldset> 
     </form>  
     <script>$(".jUiButton").button()</script> 

布尔和输入始终验证为false/null,我无法弄清原因。遵循本指南:http://sacharya.com/file-upload/

在web-inf/lib中 - 我们有commons-fileupload-1.2.2.jar和commons-io-2.0.1.jar。

任何想法?

+1

该博客的介绍性文字是[mine](http://balusc.blogspot.com/2007/11/multipartfilter.html)的翻版。感谢您提及链接。 – BalusC 2011-03-09 11:47:46

回答

3

你实际上没有提交表单。您正在使用GET请求导航到页面。

与一个提交按钮替换您的“提交”主播:

<button type="submit" class="jUiButton">Submit</button> 

你可以保持<a>但你将不得不使用JavaScript来手动提交表单。

+0

它被JavaScript的东西改变了。他的servlet的'doPost()'还有什么被调用? – BalusC 2011-03-09 11:45:14

+3

@BalusC:因为他的'doGet()'调用'doPost()'。 – Jeremy 2011-03-09 11:50:28

1

您不应该事先阅读HttpServletRequest#getInputStream()。它只能被读取一次。如果您事先已经自己阅读,Commons FileUpload将无法再读取它。摆脱你的servlet中的所有行,直到ServletFileUpload#isMultipartContent()一行。

-1

您关注的指南已过时(2008)。如果这是一个新项目,您可能希望从基于注释的方法开始。 (2010)可能会更好地遵循This guide。然后文件上传控制器将如下所示:

@Controller 
public class FileUploadContoller { 
    @RequestMapping(value = "/fileupload", method = RequestMethod.POST) 
    @ResponseStatus(HttpStatus.OK) 
    @ResponseBody 
    public String ingest(@RequestParam("file") final MultipartFile file) throws Exception { 
     if (file.isEmpty()) { 
      System.out.println("empty"); 
     } else { 
      System.out.println("not empty"); 
     } 

     // do something with file.getBytes() 

     return("ok"); 
    } 
} 

这只是控制器,您将需要添加适当的Spring配置。如果你想要走这条路,我可以进一步提供帮助。