2013-05-03 68 views
0

我在上傳文件時遇到問題。當我上傳它的實際工作中的文件我自己(本地主機),但是當我讓其他人在同一網絡中上傳自己的文件時,它給我一個錯誤:從另一臺計算機上傳文件

(The system cannot find the path specified) 
at java.io.FileInputStream.open(Native Method) 
at java.io.FileInputStream.<init>(FileInputStream.java:120) 
at sources.UploadAIP.actions.uploadAction.processRequest(uploadAction.java:49) 

這裏是我的實際代碼:

public class uploadAction extends AbstractAppAction 
{ 
    public boolean processRequest(HttpServlet servlet, HttpServletRequest request, HttpServletResponse response) 
    { 
    try{ 
     Properties appProperties = getAppProperties(); 
     String dbMap = appProperties.getProperty("dbMap"); 
     DB db = getDBConnection(dbMap); 

     String myDirectory = "C:\\tmp"; 
     String uploadedFile = request.getParameter("filename"); 
     System.out.println("srcfile: " +myDirectory); 
     System.out.println("file: " +uploadedFile); 
     String errorMessage = ""; 

     ServletContext sc  = servlet.getServletContext(); 
     String fileName   = StringUtil.stringReplace(uploadedFile,"\\","\\"); 
     int i     = fileName.lastIndexOf("\\"); 
     if (i > 0) { 
       fileName = fileName.substring(i+1); 
     } 

     File srcFile   = new File(uploadedFile); 
     File targetDirectory = new File(myDirectory); 
     String dirname   = StringUtil.stringReplace(targetDirectory.toString() ,"\\","\\"); 
     System.out.println("directory name:" +dirname); 
     File destFile   = new File(dirname+"\\"+fileName); 
     System.out.println(destFile); 
     System.out.println("here is the parent directory: " +targetDirectory);  
     if(!targetDirectory.exists()){ 
       targetDirectory.mkdirs(); 
     } 
     InputStream inStream; 
     OutputStream outStream; 
     try{ 
      inStream = new FileInputStream(srcFile); 
     outStream = new FileOutputStream(destFile); 
      byte[] buffer = new byte[4096]; 
     int length; 
     //copy the file content in bytes 
     while ((length = inStream.read(buffer)) > 0){ 
        outStream.write(buffer, 0, length); 
     } 
     outStream.close(); 
     }catch(Exception e){ 
      e.printStackTrace(); 
     } 
     fileName = StringUtil.stringReplace(uploadedFile, "\\", "\\"); 

      int u = fileName.lastIndexOf("\\"); 
      if (u > 0) 
      { 
      fileName = fileName.substring(i + 1); 
      } 

      if (!dirname.endsWith("\\")) 
      { 
      dirname = dirname + "\\"; 
      } 

      File f = new File(dirname); 
      String uploadDir = dirname; 
      System.out.println("uploadDirectory" +uploadDir); 


    } catch (Exception ex) { 
     request.setAttribute("message", ex.toString()); 
     ex.printStackTrace(); 

    } 
    return (true); 
} 

}

回答

0

您的代碼假定上傳的文件存在於同一臺本地計算機上,因爲您正在接收來自本地網絡的上傳文件,所以不成立。

這就是爲什麼它可以在本地機器上運行,但不能通過網絡運行。

要上傳文件,您需要一個多部分表單和一個能正確處理多部分請求的servlet。

本教程應該可以幫助您:

http://www.avajava.com/tutorials/lessons/how-do-i-upload-a-file-to-a-servlet.html

+0

謝謝,已經工作。 – Newbph 2013-05-03 05:53:49

相關問題