13 Replies - 1486 Views - Last Post: 03 April 2013 - 09:43 AM

#1 pazvanti  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 24-March 13

Upload file from one servlet to another

Posted 24 March 2013 - 04:46 AM

Part of a school project, I need to make a servlet that receives via POST an URL to another servlet, a file path and it will need to upload the file from the specified address.
The file isn't stored on the client, but on the server that runs the servlet.

This is my doGet method from the servlet that triggers the upload:
protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
 
        String path = request.getParameter("filePath");
        String hostAddress = request.getParameter("hostAddr");
        String fileIDString = request.getParameter("fileID");
 
        if (path == null) {
            out.print("Error path empty");
            return;
        }
        if (hostAddress == null) {
            out.print("Host Address not specified");
            return;
        }
        if (fileIDString == null) {
            out.print("File ID not specified");
            return;
        }
 
        path = path.trim();
        hostAddress = hostAddress.trim();
        fileIDString = fileIDString.trim();
 
        if (path.length() == 0) {
            out.print("Error path empty");
            return;
        }
        if (hostAddress.length() == 0) {
            out.print("Host Address not specified");
            return;
        }
        if (fileIDString.length() == 0) {
            out.print("File ID not specified");
            return;
        }
 
        int fileID = Integer.parseInt(fileIDString);
        if (fileID <= 0) {
            out.print("FileID is not OK");
            return;
        }
 
        File file = new File(path);
        if (!file.exists()) {
            out.print("File does not exist");
            return;
        }
 
        uploadFile(hostAddress, path, fileID);
 
        out.print("OK - " + hostAddress);
        return;
    }


Nothing to fancy. The problem is that I don't know how to do the "uploadFile(hostAddress, path, fileID);" method. So far I have this:
@Asynchronous
    private void uploadFile(String urlString, String exsistingFileName,
            int fileID) {
        HttpURLConnection conn;
 
        System.out.println("Sending File");
 
        if (urlString.endsWith("/")) {
            urlString += "uploadFileFromInstance";
        } else {
            urlString += "/uploadFileFromInstance";
        }
 
    }


Please note, that this isn't done via form on a website, but directly in the Servlet java code. Any help is appreciated.

Is This A Good Question/Topic? 0
  • +

Replies To: Upload file from one servlet to another

#2 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1131
  • View blog
  • Posts: 2,484
  • Joined: 05-May 05

Re: Upload file from one servlet to another

Posted 25 March 2013 - 03:48 PM

This doesn't make much sense. I know English may not be your native tongue, but it's really hard to understand what you're asking. Can you try and clarify what exactly you're trying to accomplish?

Quote

I need to make a servlet that receives via POST an URL to another servlet, a file path and it will need to upload the file from the specified address.
The file isn't stored on the client, but on the server that runs the servlet.


From what I can make out, you're saying you need a servlet that receives the URL of another servlet. Ok. Then you say "a file path". Is that the path of a file on the client or on the servlet that the URL points to? Uploading generates indicates a server receiving data from a client. Is this the case here?

Quote

The problem is that I don't know how to do the "uploadFile(hostAddress, path, fileID);" method. So far I have this:


We could skip a lot of this confusion if you could explain this method and it's parameters (maybe Javadoc style?).
Was This Post Helpful? 0
  • +
  • -

#3 pazvanti  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 24-March 13

Re: Upload file from one servlet to another

Posted 25 March 2013 - 11:59 PM

Hi and sorry for the confusion. I will try to explain a little better.

I have a client (Android app) that communicates with multiple instances of a file-store server via simple HTTP Requests (POST). Those instances can run on multiple machines (even though being only a school project they will all run on my laptop :) ). One functionality of the server is to move a file from one machine to another.

In order to do this, the client sends the file path on the machine that he wants moved, the address where the new server is located and a fileID (for logging purposes) to the server that currently hosts the file (lets call it ServerA). This is what I do in the doGet() method. If all these parameters are valid I asynchronous call uploadFile() that does another request from ServerA to ServerB, where ServerB is the server that will receive the file.

private void uploadFile(String urlString, String existingFileName, int fileID) has the following parameters:
urlString - the address of the ServerB that will receive the file
existingFileName - the path to the file on ServerA
fileID - just a file ID that will be send to ServerB

This method should do a POST on the specified address (where a servlet is mapped via @WebService("\uploadFileFromInstance").

What I don't know is how to form that request and, on serverB, how to parse it in order to get the file and save it on disk.

Hope I made everything clear.
Was This Post Helpful? 0
  • +
  • -

#4 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1131
  • View blog
  • Posts: 2,484
  • Joined: 05-May 05

Re: Upload file from one servlet to another

Posted 26 March 2013 - 05:32 AM

Much clearer now. I'd upload the file from ServerA with HttpComponents and handle it on ServerB with Commons FileUpload. There should be plenty of examples floating around.
Was This Post Helpful? 0
  • +
  • -

#5 pazvanti  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 24-March 13

Re: Upload file from one servlet to another

Posted 26 March 2013 - 11:07 AM

Thanks. I will look into those and if I have any questions hopefully you (or anyone else) will help me again. Regards :)
Was This Post Helpful? 0
  • +
  • -

#6 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1131
  • View blog
  • Posts: 2,484
  • Joined: 05-May 05

Re: Upload file from one servlet to another

Posted 26 March 2013 - 11:11 AM

Quote

Thanks. I will look into those and if I have any questions hopefully you (or anyone else) will help me again. Regards


I'd be glad to. Good luck.
Was This Post Helpful? 0
  • +
  • -

#7 pazvanti  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 24-March 13

Re: Upload file from one servlet to another

Posted 27 March 2013 - 10:42 AM

I looked over tha things you suggested and I think I almost got it, except for one problem. First, here is my full code
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import javax.ejb.Asynchronous;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

@WebServlet("/uploadRequest")
public class UploadRequest extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();

		String path = request.getParameter("filePath");
		String hostAddress = request.getParameter("hostAddr");
		String fileIDString = request.getParameter("fileID");

		if (path == null) {
			out.print("Error path empty");
			return;
		}
		if (hostAddress == null) {
			out.print("Host Address not specified");
			return;
		}
		if (fileIDString == null) {
			out.print("File ID not specified");
			return;
		}

		path = path.trim();
		hostAddress = hostAddress.trim();
		fileIDString = fileIDString.trim();

		if (path.length() == 0) {
			out.print("Error path empty");
			return;
		}
		if (hostAddress.length() == 0) {
			out.print("Host Address not specified");
			return;
		}
		if (fileIDString.length() == 0) {
			out.print("File ID not specified");
			return;
		}

		int fileID = Integer.parseInt(fileIDString);
		if (fileID <= 0) {
			out.print("FileID is not OK");
			return;
		}

		File file = new File(path);
		if (!file.exists()) {
			out.print("File does not exist");
			return;
		}

		uploadFile(hostAddress, path, fileID);

		out.print("OK - " + hostAddress);
		return;
	}

	@Asynchronous
	private void uploadFile(String urlString, String exsistingFileName,
			int fileID) {

		System.out.println("Sending File");

		if (urlString.endsWith("/")) {
			urlString += "uploadFileFromInstance";
		} else {
			urlString += "/uploadFileFromInstance";
		}

		DefaultHttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(urlString);

		MultipartEntity reqEntity = new MultipartEntity(
				HttpMultipartMode.BROWSER_COMPATIBLE);

		try {
			reqEntity.addPart("fileID", new StringBody(fileID + ""));
			FileBody bin = new FileBody(new File(exsistingFileName));
			reqEntity.addPart("attachment", bin);

			httppost.setEntity(reqEntity);

			System.out
					.println("executing request " + httppost.getRequestLine());
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity resEntity = response.getEntity();

			if (resEntity != null) {
				String page = EntityUtils.toString(resEntity);
				System.out.println("PAGE :" + page);
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}



The thing is that now, if I enter the URL in the browser I get HTTP Status 404. If I comment out the body of the method "uploadFile", it works (obviously, without the actual upload). It is just as DefaultHttpClient is dissabling the @WebServlet(). Any suggestions how I may fix this? Thanks.
Was This Post Helpful? 0
  • +
  • -

#8 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1131
  • View blog
  • Posts: 2,484
  • Joined: 05-May 05

Re: Upload file from one servlet to another

Posted 27 March 2013 - 10:59 AM

What URL string are you using?
Was This Post Helpful? 0
  • +
  • -

#9 pazvanti  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 24-March 13

Re: Upload file from one servlet to another

Posted 27 March 2013 - 11:10 AM

The URL is this: http://localhost:808...r/uploadRequest
If the content of the method uploadFile is commented out, I get "Error path empty". So it works. If the body is left, I get Error 404 on the same URL.
Was This Post Helpful? 0
  • +
  • -

#10 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1131
  • View blog
  • Posts: 2,484
  • Joined: 05-May 05

Re: Upload file from one servlet to another

Posted 27 March 2013 - 11:34 AM

Looks like a valid request to me. Have you looked at error log?
Was This Post Helpful? 0
  • +
  • -

#11 pazvanti  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 24-March 13

Re: Upload file from one servlet to another

Posted 27 March 2013 - 11:39 AM

In the eclipse console nothing is written. It shows the server.log file from Glassfish. Forgot to mention that I am using Glassfish as the application server.
Was This Post Helpful? 0
  • +
  • -

#12 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1131
  • View blog
  • Posts: 2,484
  • Joined: 05-May 05

Re: Upload file from one servlet to another

Posted 27 March 2013 - 12:41 PM

The Eclipse console should tell you where to find server.log. It's under the the domain\domainX\logs directory in the glassfish folder. Definitely check it out. Mine is showing a ClassCastException when I run your servlet, and I have HttpComponents and FileUpload jars on the build path. That may be what's happening to you too. I really can't spend anymore time on this, but if I get a chance I'll come back to it later.
Was This Post Helpful? 0
  • +
  • -

#13 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1131
  • View blog
  • Posts: 2,484
  • Joined: 05-May 05

Re: Upload file from one servlet to another

Posted 29 March 2013 - 01:42 PM

Any luck?
Was This Post Helpful? 0
  • +
  • -

#14 pazvanti  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 24-March 13

Re: Upload file from one servlet to another

Posted 03 April 2013 - 09:43 AM

Sorry for my late reply. I only have time on Wednesday to work on this project. Just managed to get it to work. Thank you for your help.
Just in case anyone is having the same problem: even thought I added the jars to the java build path, they weren't added to the Deployment Assembly. After that could send the file via the request. After downloading Apache CommonsIO everything worked and the file was uploaded.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1