【发布时间】:2012-03-12 01:50:51
【问题描述】:
我的上传代码如下:
String end = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
try {
URL url = new URL(ActionUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestMethod("POST");
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Accept", "text/*");
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
DataOutputStream ds = new DataOutputStream(con.getOutputStream());
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data;" + "name=\"folder\"" + end + end);
ds.write(SavePath.getBytes("UTF-8"));
ds.writeBytes(end);
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data;" + "name=\"Filedata\"; filename=\"");
ds.write(FileName.getBytes("UTF-8"));
ds.writeBytes("\"" + end);
ds.writeBytes(end);
FileInputStream fStream = new FileInputStream(uploadFilepath+""+FileName);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
int pro = 0;
while((length = fStream.read(buffer)) != -1) {
ds.write(buffer, 0, length);
}
ds.writeBytes(end);
ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
fStream.close();
ds.flush();
InputStream is = con.getInputStream();
int ch;
StringBuffer b = new StringBuffer();
while((ch = is.read()) != -1) {
b.append((char)ch);
}
ds.close();
}
catch(Exception e) {
e.printStackTrace();
}
它可以在上传较小的文件时工作。 但是,当更多 16 mb 时,它会上传失败并显示 OutOfMemory 错误。 我认为这是因为将所有数据都放在缓冲区中。 所以我想让它在缓冲区保存 1024 个字节的同时发送数据。 但我不知道这样做。 有人可以帮我做吗?
【问题讨论】:
-
您可以尝试添加 ds.flush();进入 while((length = fStream.read(buffer)) != -1) { ds.write(buffer, 0, length);以便它可以将所有数据刷新到服务器...(我假设服务器将等待直到 ds.writeBytes(twoHyphens + boundary + twoHyphens + end); 调用)
-
我试过了。它仍然在同一行出现相同的错误。
标签: android upload out-of-memory