How to upload .txt file to http server? - android

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

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

Related

Android http client upload not working in some server

I m using the following code to upload file to a server. It works quite well in localhost and bluehost. But it is not working in some hosting like(Go Daddy). Would anybody explain why???
data = IOUtils.toByteArray(inputStream);
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(upload_url);
InputStreamBody inputStreamBody = new InputStreamBody(new ByteArrayInputStream(data), fileName);
CustomMultiPartEntity multipartEntity = new CustomMultiPartEntity();
multipartEntity.setUploadProgressListener(this);
multipartEntity.addPart("pdf", inputStreamBody);
multipartEntity.addPart("title", new StringBody(title));
multipartEntity.addPart("subject", new StringBody(subject));
multipartEntity.addPart("college", new StringBody(college));
multipartEntity.addPart("stream", new StringBody(stream));
multipartEntity.addPart("branch", new StringBody(branch));
multipartEntity.addPart("userID", new StringBody(String.valueOf(userid)));
httpPost.setEntity(multipartEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
I performed a lot of testing. When I retrieve the values via $_POST[] in the server, the value is null. HttpUrlConnection works in all server. But we have to write everything ourselves. I mean why to write so much code from scratch for a simple function like upload... Is there no library with simple callbacks.?
HttpClient, HttpPost.. are deprecated in API 22, So you should try to use HttpURLConnection instead.

Cannot set header to multipart/form-data for HttpPost

I'm trying to post some compressed data plus text to a perl program on a web server but cannot change the header from octet-stream to multipart/form-data.
My code is:-
HttpClient httpclient = new DefaultHttpClient();
String url = "http://webaddress/perl.pl";
HttpPost httppost = new HttpPost(url);
httppost.setHeader("Content-Type","multipart/form-data");
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
try {
entity.addPart("mtdata",new ByteArrayBody(data, file.getLastPathSegment()));
entity.addPart("email", new StringBody(strUserName));
entity.addPart("mtfilename", new StringBody(file.getLastPathSegment()));
httppost.setEntity(entity);
HttpResponse httpresponse = httpclient.execute(httppost);
HttpEntity resEntity = httpresponse.getEntity();
response = EntityUtils.toString(resEntity);
}
The raw data being received is :-
Buffer = --FfT4ZNRUCPw6yONkpSsXNkA3WA2l6fvy53
Content-Disposition: form-data; name="mtdata"; filename="filename"
Content-Type: application/octet-stream <<=== cannot change this
... Some binary data ...
What am I doing wrong?
In the end I found that the best way was to save it as a file and then post the file using MultipartEntity with a FileBody explicitly stating the Content-Type.
The code I used was:-
pairs.addPart("File", new FileBody(fout,"multipart/form-data"));
As an aside, I also found that I needed to use ZipOutputStream rather than GZIPOutputStream so that I could add the uncompressed file name.
Code for that was:-
data = bos.toByteArray();
OutputStream fos = new FileOutputStream(extStorageDirectory + newfilename);
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos));
try {
ZipEntry entry = new ZipEntry(file.getLastPathSegment());
zos.putNextEntry(entry);
zos.write(data);
zos.closeEntry();
}
finally {
zos.close();
}
fos.close();
Try insert
httppost.addHeader("Content-Type", "multipart/form-data");
and remove
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

Uploading file via form into GAE from Android

I have an app on GAE at: http://1.myawesomecity.appspot.com/
FIXED:
HttpPost post = new HttpPost("http://1.myawesomecity.appspot.com/");
http_client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
String result = EntityUtils.toString( http_client.execute(post).getEntity(), "UTF-8");
String actualURL = result.substring(result.indexOf("http://"), result.indexOf("\" method"));
Log.w("asdf", "url " + actualURL );
post = new HttpPost(actualURL);
http_client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
String mime_type = "image/png";
File file = new File( filename ); //context.getFilesDir(),
entity.addPart( "myFile", new FileBody( file, mime_type));
post.setEntity( entity );
String res = EntityUtils.toString( http_client.execute(post).getEntity(), "UTF-8");
Log.w("asdf", res);
The above grabs the ACTUAL upload URL from the GAE server, and passes in the file as dictated by the CORRECT answer below.
Old Question:
As you can see, if you choose a file and hit submit, it will 404, but the file actually does get stored (as long as it is not too big, < 100kb). Don't type in anything in the first text field.
Now, putting aside how this particular app is barely functional, I'm trying to upload a file from Android onto this server.
The site's upload script uses blobstore, and the file field's name is "myFile".
Now in my Android app, I have:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(<my app's url>);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("myFile", <path to a file selected by user> ) );
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
This throws an exception.
How is this any different from me going to my site through a browser, choosing a file, and hitting submit? Why does going through a browser actually go through with uploading the file, when the Android code does not?
I know that my filepath is valid. Is there something I'm doing wrong? or is clicking on "submit" from a browser different from executing a httpclient from Android?
Uploading file to a blobstore on GAE is a two step process:
first you need to get a proper URL where to POST your data, usually people use something like "/bloburl" handler for that purpose
when you have blob upload URL, you use it in your request.
the file you send does not go as NameValuePair, it's supposed to go as a MultiPartEntity.
here's the code that works (you'll need apache http library for MultiPartEntry support):
DefaultHttpClient http_client = new DefaultHttpClient();
HttpGet http_get = new HttpGet(Config.BASE_URL + "bloburl");
HttpResponse response = http_client.execute(http_get);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String first_line = reader.readLine();
Log.w(TAG, "blob_url: " + first_line);
HttpPost post = new HttpPost(first_line);
http_client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
mime_type = "application/zip";
File file = new File( context.getFilesDir(), filename );
entity.addPart( "file", new FileBody( file, mime_type));
post.setEntity( entity );
String result = EntityUtils.toString( http_client.execute(post).getEntity(), "UTF-8");
Log.i(TAG, result);

Trouble Uploading Image from Android to Rails Server Using PaperClip

I'm trying to upload images to my rails server from Android. All my other data uploads, but I get a "Error invalid body size" error. It has to do with the image. Below is my code. Help?!
public void post(String url) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("content_type","image/jpeg");
try {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("picture_file_name", new StringBody("damage.jpg"));
File file = new File((imageUri.toString()));
entity.addPart("picture", new FileBody(file, "image/jpeg"));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
} catch (IOException e) {
e.printStackTrace();
}
}
I've tried removing the browser compatible parameter, but it doesn't help. my image is being stored as an URI called imageUri. I'm using paperclip gem.
thanks!
This is how I solved.
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for (NameValuePair nameValuePair : nameValuePairs) {
if (nameValuePair.getName().equalsIgnoreCase("picture")) {
File imgFile = new File(nameValuePair.getValue());
FileBody fileBody = new FileBody(imgFile, "image/jpeg");
multipartEntity.addPart("post[picture]", fileBody);
} else {
multipartEntity.addPart("post[" + nameValuePair.getName() + "]", new StringBody(nameValuePair.getValue()));
}
}
httpPost.setEntity(multipartEntity);
HttpResponse response = httpClient.execute(httpPost, httpContext);
This will produce a POST like this:
{"post"=>{"description"=>"fhgg", "picture"=>#<ActionDispatch::Http::UploadedFile:0x00000004a6de08 #original_filename="IMG_20121211_174721.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"post[picture]\"; filename=\"IMG_20121211_174721.jpg\"\r\nContent-Type: image/jpeg\r\nContent-Transfer-Encoding: binary\r\n", #tempfile=#<File:/tmp/RackMultipart20121211-7101-3vq9wh>>}}
In the rails application your model attributes must have the same name you use in your request
, so in my case
class Post < ActiveRecord::Base
attr_accessible :description, :user_id, :picture
has_attached_file :picture # Paperclip stuff
...
end
I have also disabled the CSRF token from the rails application.

android httpclient

How to transfer a 50mb file to web server using httppost.
When trying to transfer the file it shows out of memory error.
can we use chuncked encoding? how? give some code snippets.
Thank you.
Edit:
Here's the code:
InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(f), -1);
reqEntity.setContentType("binary/octect-stream");
reqEntity.setChunked(true);
httppost.setEntity(reqEntity);
Use InputStreamEntity as it does not load the whole file in memory. Do something like this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/upload");
File file = new File("/path/to/myfile");
FileInputStream fileInputStream = new FileInputStream(file);
InputStreamEntity reqEntity = new InputStreamEntity(fileInputStream, file.length());
httppost.setEntity(reqEntity);
reqEntity.setContentType("binary/octet-stream");
HttpResponse response = httpclient.execute(httppost);
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
responseEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();

Categories

Resources