2017-09-05 91 views
-1

我能夠上傳局部而不是圖像能夠遠程上載(即,另一機)。這裏是代碼..上傳圖像,以遠程位置的文件夾中的java

@WebServlet(「/ UploadServ」 )

公共類UploadServlet延伸的HttpServlet {

private static final String UPLOAD_DIR1 = "\\\\ip-address\\C$\\upload\\"; 
public UploadServlet() { 
    super(); 
} 
protected void doGet(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException { 
    doPost(request, response); 
} 

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

    boolean isMultipart = ServletFileUpload.isMultipartContent(request); 
    if (!isMultipart) { 
    } else { 
     try { 
      List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()) 
        .parseRequest(new ServletRequestContext(request)); 

      for (FileItem item : multiparts) { 
       if (!item.isFormField()) { 
        String name = new File(item.getName()).getName(); 
        item.write(new File(UPLOAD_DIR1 + name)); 
       } 
      } 
      // File uploaded successfully 
      System.out.println("File uploaded successfully"); 
     } catch (Exception ex) { 
      ex.printStackTrace(); 
      System.out.println("File uploaded failed.."); 
     } 
    }} 
    request.getRequestDispatcher("response.jsp").forward(request, response); 
} 
+0

你需要告訴我們你有什麼問題。 –

+0

如何將圖像從一臺機器上傳/保存到其他機器?如果我編寫UPLOAD_DIR1 =「C:\\ upload \\」,那麼它的工作正常。但我只是想在不在同一臺機器上的另一臺機器上傳圖像。 – Kumar

+0

您發佈的代碼是服務器端代碼。如果你想要一臺服務器轉移到另一臺服務器上,那麼考慮使用ftp –

回答

0

爲了創建相對於所述web內容根( 「/」)正確的文件夾的URL,我用下面的代碼

final String uploadDir = request.getRealPath("/ip-address/C$/upload"); 

然後,只需創建一個新的文件對象

File file = new File(uploadDir, fileName); 

注意getRealPath()現在已經過時,但應該仍然工作。根據這個答案(Recommended way to save uploaded files in a servlet application)有更好的方法來指定一個上傳文件夾,但我還沒有嘗試過任何這些方法。

相關問題