我已经审核了几个相关的问题(比如这个代码已经发布了很多,但由于某些原因对我不起作用:How do I add REQUEST values to an HTTP POST method using multipart to upload a file to a PHP server in Android?)并尝试了几个解决方案,但我在服务器上查看的文件是不可解码为jpg。我的上传工作在iPhone应用程序,但现在当我移植到Android时,我无法找到正确的方法来做到这一点。服务器端是一个asp.net流媒体文件上传API。
这是我的base64编码逻辑:
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);
这是postBitmap代码
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);
传输前和服务器上的文件大小相同,所以我不认为这是传输问题,更可能是编码问题。
以下是我正在尝试移植的有效iOS代码:
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];
非常感谢! 斯科特
答案 0 :(得分:0)
尝试使用Base64将图像编码为String,在另一端使用Server,通过解码将Base64的String更改为Image。查看链接[http://developer.android.com/reference/android/util/Base64.html] [1]
[1]:2.2支持http://developer.android.com/reference/android/util/Base64.html。我们还提供少于2.2版本设备的Base64.java。