2011-11-07 148 views
0

我在JSP邊有這樣的代碼上傳的文件:我怎樣才能在JSP形式

<body> 
    <form action="upload" method="post" enctype="multipart/form-data"> 
     <table> 
      <tr> 
       <td>Select File : </td> 
       <td><input name="file" type="file"/> </td> 
      </tr> 
      <tr> 
       <td>Enter Filename : </td> 
       <td><input type="text" name="photoname" size="20"/> </td> 
      </tr> 
     </table> 
     <p/> 
     <input type="submit" value="Upload File"/> 
    </form> 
</body> 

這上傳單個文件。

而在servlet中,我的代碼:

protected void doPost(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException { 
     response.setContentType("text/html;charset=UTF-8"); 
     PrintWriter out = response.getWriter(); 
     try { 

      Part p1 = request.getPart("file"); 
      InputStream is = p1.getInputStream(); 


      Part p2 = request.getPart("photoname"); 
      Scanner s = new Scanner(p2.getInputStream()); 
      String filename = s.nextLine(); 



      // get filename to use on the server 
      String outputfile = "C:\\Documents and Settings\\Sherman\\Desktop\\ImoveiSP\\ImoveiSP\\DB_Scripts" + filename + ".jpg"; 
      //outputfile = outputfile + ".jpg"; 
      //System.out.println("out = " + outputfile); 
      FileOutputStream os = new FileOutputStream(outputfile); 

      // write bytes taken from uploaded file to target file 
      int ch = is.read(); 
      while (ch != -1) { 
       os.write(ch); 
       ch = is.read(); 
      } 
      os.close(); 
      out.println("<h3>File uploaded successfully! </h3>"); 


      File file = new File("C:\\Documents and Settings\\Sherman\\Desktop\\ImoveiSP\\ImoveiSP\\DB_Scripts" + filename + ".jpg"); 
      uploadAmazon(file, "ibagem", ""); 

     } catch (Exception ex) { 
      out.println("Exception -->" + ex.getMessage()); 
     } finally { 
      out.close(); 
     } 
    } 

這個servlet需要上傳的文件並將其保存到磁盤。

我有兩個問題,關於這個代碼:

  1. 在JSP中的一面,我怎麼能強迫用戶只發送jpg或.MPG文件?
  2. 如果我把更多的一個輸入上傳到jsp端,我如何在servlet中接收所有內容?
+0

[如何在JSP/Servlet中上傳文件?](http://stackoverflow.com/questions/2422468/how-to-upload-files-in-jsp-servlet/2424824#2424824) – BalusC

回答

1

我推薦使用Commons FileUpload來處理所有這些;它使事情變得更容易。 See the user guide for details

處理多個文件與處理單個文件相同。

我建議將該絕對路徑名移動到配置參數,順便說一句。