-1

I am able to upload image locally but not able to upload remotely(i.e another machine).Here is the code..

@WebServlet("/UploadServ")

public class UploadServlet extends 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);
}
K-T
  • 1
  • 1
  • 5
  • You need to tell us what problems you are having. – Scary Wombat Sep 05 '17 at 05:22
  • how i can upload/save image from one machine to other machine?If i write UPLOAD_DIR1 = "C:\\upload\\" then its work fine. but i just want to upload the images in another machine not in same machine. – K-T Sep 05 '17 at 05:38
  • The code that you have posted is server side code. If you want one server to transfer to another server then consider using ftp – Scary Wombat Sep 05 '17 at 05:43
  • Thanks Scary Wombat . Can you give me a sample of code so that i can understand. – K-T Sep 05 '17 at 05:56
  • why, is your browser broken? Can you not search for code yourself? – Scary Wombat Sep 05 '17 at 05:56
  • The problem is in your UPLOAD_DIR1 syntax. I will post the correct syntax for the URL when I get home (because I can't remember the exact syntax right now) – dsp_user Sep 05 '17 at 06:26

1 Answers1

0

In order to create the correct folder URL relative to the web content root ("/"), I used the following code

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

Then just create a new File object

File file = new File( uploadDir, fileName);

Note that getRealPath() is now deprecated but should still work. According to this answer here ( Recommended way to save uploaded files in a servlet application ) there are better ways to specify an upload folder but I haven't tried any of these methods.

dsp_user
  • 2,061
  • 2
  • 16
  • 23