Question

Hi I am working on web application where I need to transfer any type of file from on web app to another.

I able to transfer data as string format but I am facing problem when I need to transfer files. First I show code used to transfer data as parameter from sender to receiver.

Sender Side:

HttpClient client = new HttpClient();  
HttpMethod method = new PostMethod("http://192.168.1.108:8081/Receiver-Server/registerAction");  
List<NameValuePair> pairs = new ArrayList<NameValuePair>();  
NameValuePair nvp1= new NameValuePair("name", "Aniket");
NameValuePair nvp2= new NameValuePair("Age", "26");

method.setQueryString(new NameValuePair[]{nvp1,nvp2});  
int statusCode = client.executeMethod(method);
System.out.println(statusCode);

Now the receiver side,

String userName = request.getParameter("name");
String age = request.getParameter("Age");

Above I am successfully getting data. So now I need to transfer any type of file, but getting problem.

So can anyone help me to solve this issue, any hint or tutorial is better to be appreciated.

Was it helpful?

Solution

Transferring the file requires multipart HTTP request. HTTPClient recently introduced MultipartEntityBuilder to make it easy to develop. Complete project can be downloaded from GitHub

HttpClient code that uploads a file

CloseableHttpClient httpClient = HttpClients.createDefault();
try {
    FileBody bin = new FileBody(file);
    HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).build();
    HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(reqEntity);

    CloseableHttpResponse postResponse = httpClient.execute(httpPost);
    try {
        writer.println(postResponse.getStatusLine());
        HttpEntity postResponseEntity = postResponse.getEntity();
        if (postResponseEntity != null) {
            writer.println(EntityUtils.toString(postResponseEntity));
        }
    } finally {
        postResponse.close();
    }
} finally {
    httpClient.close();
}

A Servlet that use FileUpload to receive the file

DiskFileItemFactory factory = new DiskFileItemFactory();
ServletContext servletContext = this.getServletConfig().getServletContext();
File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
factory.setRepository(repository);

ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
    if (!item.isFormField()) {
        writer.println("fieldName = " + item.getFieldName());
        writer.println("fileName = " + item.getName());
        writer.println("contentType = " + item.getContentType());
        writer.println("size [bytes] = " + item.getSize());
        File uploadedFile = File.createTempFile("temp", ".txt");
        item.write(uploadedFile);
        writer.println("stored as  " + uploadedFile.getAbsolutePath());
    }
}

I think that the code is so easy that it does not need explanation but feel free to ask.

One important note: never ever use supplied file name as filename of created file. This is a security risk.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top