Android - 将大图像上传到服务器
问题描述:
我想让我的应用程序使用下面的代码将图像上传到网络服务器。它有时会起作用,但似乎也会因内存错误而失败。如果文件大小很大,有人可以发表一个如何完成这个任务的例子吗?此外,我正在构建这个支持1.5和以上。我不介意给我的代码在上传之前调整图像的大小。Android - 将大图像上传到服务器
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlString);
File file = new File(nameOfFile);
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();
答
你有两个选择,使你的代码是可行的。
您应该使用多部分方法来上传较大的文件。我在我的代码中使用了哪些内容。 Its Apache code。 (是的,您可以轻松地将其移植到您的Android项目中)。
您可以最小化图像分辨率。通过使用SampleSize标志, 按照this链接。
我希望它有帮助。
+0
您可以发布第二个解决方案的示例代码。我宁愿这样做,因为一旦它打到我的服务器,我就调整它的大小。非常感谢您的快速响应。 – BBCM 2011-02-09 05:36:32
答
你应该仔细看看连接的setChunkedStreamingMode。 。或者,事实上,使用MultipartEntity(这是阿帕奇httpcomponents库 - 你会很容易找到这个地段的解决方案
为调整图像大小,这是相当简单:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2; // look at the link Rajnikant gave for more details on this
Bitmap bitmap = BitmapFactory.decodeFile(filename, options);
// here you save your bitmap to whatever you want
但内存占用过多.. 。
答
您可以尝试上传图片下面的代码。
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
MultipartEntity multiPart = new MultipartEntity();
multiPart.addPart("my_picture", new FileBody(new File(IMG_URL)));
httpPost.setEntity(multiPart);
HttpResponse res = httpClient.execute(httpPost);
时出现内存问题所产生的图像是不完整的,似乎,这意味着它在它下面磨片灰色像素重新失败。 – BBCM 2011-02-09 05:22:03
您是否找到了该问题的解决方案? @BBCM – Amina 2014-05-09 10:51:00