【发布时间】:2016-05-31 12:49:53
【问题描述】:
我附上 3 张图片(每张 4.8Mb)并发布到服务器。在处理第三张图像时,我收到“OutOfMemoryError”。 下面是我得到上述错误的代码 sn-p。
dos.write(buffer, 0, bufferSize);
我只在注释 2,操作系统版本 4.4.2 中面临执行
以下是为处理图像而编写的完整代码sn-p。
for (int i = 0; i < attachmentUri.size(); i++) {
String fileName ="attachment"+(i+1);
File file = new File(attachmentUri.get(i));
if (file.exists()) {
dos.writeBytes("--" + Constants.IMAGE_BOUNDRY + LINE_FEED);
uploadAttachments(dos, fileName,attachmentUri.get(i), LINE_FEED);
} else {
Log.i("Attachment not found");
}
}
void uploadAttachments(DataOutputStream dos,String filename,String filePath,String lineEnd) {
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {
FileInputStream inputStream = new FileInputStream(filePath);
dos.writeBytes("Content-Disposition: form-data; name=\""+ filename + "\";filename=\""+ (filePath.substring(filePath.lastIndexOf("/")+1)) + "\"" + lineEnd + "Content-Type: image/jpeg; charset=UTF-8" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = inputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = inputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = inputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = inputStream.read(buffer, 0, bufferSize);
}
dos.writeBytes(lineEnd);
inputStream.close();
} catch (IOException ioe){
Log.e(e.getMessage());
}
}
如何解决问题?
【问题讨论】:
-
增加maxBufferSize = 5* 1024 * 1024 insted of maxBufferSize = 1* 1024 * 1024
-
@sachi 分享你的连接代码....!!!
-
httpURLConnection.setChunkedStreamingMode(1024);并在stackoverflow上尝试这个答案...stackoverflow.com/a/9630475/3678308
-
@ExceptionLover URLConnection 连接 = _url.openConnection(); HttpsURLConnection httpConnection = (HttpsURLConnection) 连接; httpConnection.setConnectTimeout(45000); httpConnection.setReadTimeout(45000); httpConnection.setDoOutput(true); httpConnection.setDoInput(true); httpConnection.setRequestMethod("PUT"); httpConnection.setRequestProperty("Content-Type","multipart/form-data;boundary=" + Constants.IMAGE_BOUNDRY); httpConnection.connect();
-
再次尝试此代码..... URLConnection connection = _url.openConnection(); HttpsURLConnection httpConnection = (HttpsURLConnection) 连接; httpConnection.setConnectTimeout(45000); httpConnection.setReadTimeout(45000); httpConnection.setChunkedStreamingMode(1024); httpConnection.setDoOutput(true); httpConnection.setDoInput(true); httpConnection.setRequestMethod("PUT"); httpConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + Constants.IMAGE_BOUNDRY); httpConnection.connect();
标签: android android-asynctask android-image