android - 从文件中读取 jpg 并上传/发布到 android 中的网络服务器

标签 android http

我已经回顾了几个相关的问题(例如这段代码被发布了很多但由于某种原因对我不起作用: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];

非常感谢! 斯科特

最佳答案

尝试使用Base64将图片编码为String,在Server的另一端,通过解码将Base64的String改为Image。检查链接 [http://developer.android.com/reference/android/util/Base64.html][1]

[1]: http://developer.android.com/reference/android/util/Base64.html从 2.2 开始支持。我们还为低于 2.2 版本的设备提供了 Base64.java。

关于android - 从文件中读取 jpg 并上传/发布到 android 中的网络服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9857840/

相关文章:

javascript - jwplayer 可以在桌面上运行,但不能在所有移动设备上运行,为什么?

rest - http post - 如何发送授权 header ?

http - 重定向到 "/"或 index.html

javascript - Moment.js 不接受查询字符串作为有效输入

javascript - NodeJS 服务器 - 客户端对于响应状态 500 的行为有所不同,具体取决于响应正文

http - 在 https 上使用国际电话输入

Java 2 Objective-C NSArray

android - 向不同屏幕尺寸的布局添加额外的元素

android - 背景可绘制不起作用

android - 数据库 "CREATE TABLE IF NOT EXISTS"语法错误