将图像从本地窗口上传到java中的远程位置文件夹

时间:2017-09-05 05:21:06

标签: java jsp

我可以在本地上传图像,但无法远程上传(即另一台机器)。这是代码..

@WebServlet(" / UploadServ&#34)

公共类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);
}

1 个答案:

答案 0 :(得分:0)

为了创建相对于Web内容根目录(“/”)的正确文件夹URL,我使用了以下代码

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

然后只需创建一个新的File对象

File file = new File( uploadDir, fileName);

请注意,getRealPath()现已弃用,但仍应有效。根据这里的答案(Recommended way to save uploaded files in a servlet application),有更好的方法来指定上传文件夹,但我还没有尝试过任何这些方法。