0

I want to upload a .txt file(only) from a device to my server. How can I do this? I also want to be able to download another .txt file from the server to a device.

Any ideas where to start?

Thanks..

ouii
  • 1
  • 1
  • 1

1 Answers1

3

Use HttpClient and HttpPost from the HttpComponents library available for java to post a file to your server via http. You can use the MultipartEntity and/or FileEntity class for representing your file data.

see example here, or see multipart example below:

HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

HttpPost httppost = new HttpPost(url);     

// add file content and metadata
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(targetFile, "image/jpeg");
mpEntity.addPart("userfile", cbFile);
mpEntity.addPart( "commentText", new StringBody(commentText, "text/plain",
                Charset.forName( "UTF-8" )));

httppost.setEntity(mpEntity);

HttpResponse response = httpclient.execute(httppost);
Community
  • 1
  • 1
Mike Marshall
  • 7,788
  • 4
  • 39
  • 63