我想从诺基亚手机上传一个大文件到服务器,我使用下面的代码。此代码适用于小文件。当我想上传一个更大的文件(大约10mb)时,我得到一条内存不足的消息。有谁知道如何转换此代码以使用上传文件 多个httpConnections,每个连接发送一个文件块。我们假设服务器支持此功能。
fc = (FileConnection)Connector.open("file:///myfile", Connector.READ);
is = fc.openInputStream();
// opening http connection and outputstream
HttpConnection http = (HttpConnection)Connector.open(url, Connector.WRITE);
http.setRequestMethod(HttpConnection.POST);
http.setRequestProperty("Content-Type", type);
http.setRequestProperty("Connection", "close");
OutputStream os = http.openOutputStream();
int total = 0;
while (total < fileSize) {
byte b[] = new byte[1024];
int length = is.read(b, 0, 1024);
os.write(b, 0, length);
total += length;
}
os.flush();
int rc = http.getResponseCode();
os.close();
http.close();
答案 0 :(得分:1)
尝试在os.flush()
循环内移动while
调用,以便每次都刷新缓冲区。因为它是在您通过网络发送之前将整个文件读入内存的时刻。
如果这不能解决问题,我建议使用profiler在模拟器中运行代码,以便更好地了解内存耗尽的位置。
答案 1 :(得分:1)
尝试在while循环之前移动缓冲区初始化byte b[] = new byte[1024];
- 您不需要每次都重新创建它。并尝试将System.gc()
放入循环中 - 它可能会有所帮助(或可能不会)。
此外,当您致电fc.openInputStream