张贴在Android的一个大文件 [英] Posting a large file in Android

查看:99
本文介绍了张贴在Android的一个大文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有时会得到一个的OutOfMemoryError 张贴在Android的一个大文件时。这是code我使用。难道我做错了什么?

I sometimes get an OutOfMemoryError when posting a large file in Android. This is the code I'm using. Am I doing something wrong?

HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
ostream = new DataOutputStream(con.getOutputStream());
byte[] buffer = new byte[1536];
int count;
while ((count = fileInput.read(buffer)) != -1) {
    ostream.write(buffer, 0, count); // This sometimes causes OutOfMemoryError
}
ostream.flush();

会调用 ostream.flush(),而循环里面有什么好处?

Would calling ostream.flush() inside the while loop do any good?

推荐答案

如果你做这样的,整个POST必须在内存中缓存。这是因为它需要先发送的Content-Length头。

If you do it like that, the whole POST must be buffered in memory. This is because it needs to send the Content-Length header first.

相反,我觉得你要使用Apache HTTP库,其中的 FileEntity 。这将让它计算出长度读取文件​​之前。您可以使用<一个href="http://stackoverflow.com/questions/3038409/how-to-send-http-post-request-and-recieve-response/3038747#3038747">this回答为出发点。但是,第二个参数FileEntity构造应该是一个MIME类型(如图像/ PNG,text / html的,等等)。

Instead, I think you want to use the Apache HTTP libraries, including FileEntity. That will let it figure out the length before reading the file. You can use this answer as a starting point. But the second parameter to the FileEntity constructor should be a mime type (like image/png, text/html, etc.).

这篇关于张贴在Android的一个大文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆