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

jm81lzqq  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(294)

我可以在本地上传图片,但不能远程上传(即另一台机器)。下面是代码。。
@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);
}
9nvpjoqh

9nvpjoqh1#

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

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

然后创建一个新的文件对象

File file = new File( uploadDir, fileName);

请注意 getRealPath() 现在已弃用,但仍应有效。根据这里的答案(在servlet应用程序中保存上传文件的推荐方法),有更好的方法来指定上传文件夹,但我没有尝试过这些方法中的任何一种。

相关问题