Read jpg from file and upload / publish to web server in android

I looked at a few related questions as well (for example, this code has been posted a lot, but doesn't work for me for some reason: How do I add REQUEST values ​​to the HTTP POST method using multipart to upload a file to a PHP server in Android? ) And tried to create couple of solutions but my file when viewed on server cannot be decoded as jpg. I have a download working in an iPhone app, but now that I am porting to android, I cannot find the correct way to do it. Server side is asp.net streaming api file download.

Here is my base64 encoding logic:

Bitmap fileToUpload = BitmapFactory.decodeFile(obs.getPhotoLocation());    
ByteArrayOutputStream stream = new ByteArrayOutputStream();
fileToUpload.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] image = stream.toByteArray();                        
String data = Base64.encodeToString(image, true);
new HttpConnection(handler).postBitmap(url.toString(), data);

      

Here is the postBitmap code

HttpPost httpPostBitmap = new HttpPost(url);
httpPostBitmap.addHeader("Content-type", "image/jpg");
httpPostBitmap.addHeader("Connection", "Keep-Alive");
httpPostBitmap.setEntity(new StringEntity(data));
response = httpClient.execute(httpPostBitmap);

      

The file before transfer and on the server are the same sizes, so I don't think this is a transfer issue and most likely an encoding issue.

Here is the working iOS code I am trying to execute.

NSURL *uploadUrl = [NSURL URLWithString:FILEUPLOAD_URL];
UIImage *testImage = [Helpers getImageFromPhoto:self.obsToTransmit.observationPhoto];
NSData *imageData = UIImageJPEGRepresentation(testImage, 1.0);

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:@"%d", [imageData length]];
[request addValue:@"image/jpg" forHTTPHeaderField:@"Content-type"];
[request setHTTPMethod:@"POST"];
[request addValue:msgLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:imageData];

theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

      

Thank! Scott

+3


source to share


1 answer


Try to use Base64 to encode the image to String, and on the other end on the server, change the String Base64 to Image by decrypting it. Check the link [http://developer.android.com/reference/android/util/Base64.html] [1]



[1]: http://developer.android.com/reference/android/util/Base64.html which is supported in version 2.2. We also have Base64.java for less than 2.2 versions.

0


source







All Articles