2013-05-03 35 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

相关问题