ouii
ouii

Reputation: 1

How to upload .txt file to http server?

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..

Upvotes: 0

Views: 5033

Answers (1)

Mike Marshall
Mike Marshall

Reputation: 7850

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);

Upvotes: 3

Related Questions