我有一个android应用程序试图通过API接口将照片上传到web服务器。只要图像大小不太大(在1280x800左右的某个地方失败),该方法就可以很好地工作。在这里,可以工作的代码将缩小图像,但对于较大的图像则会失败。有什么建议吗?
public void uploadPhoto(FileInputStream fileInputStream, String session_key) throws IOException, ClientProtocolException {
URL connectURL = new URL(API_ENDPOINT_URL + "session_key="
+ session_key + "&method=" + ApiMethods.UPLOAD_PHOTO);
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
HttpURLConnection conn = (HttpURLConnection) connectURL.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+ boundary);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""+ "file.png" + "\"" + lineEnd);
dos.writeBytes(lineEnd);
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
Log.d(TAG, " BytesREad:" + bytesRead);
while (bytesRead > 0) {
Log.d(TAG, " BytesREad in while:" + bytesRead);
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dos.flush();
InputStream is = conn.getInputStream();
int ch;
StringBuffer b = new StringBuffer();
while ((ch = is.read()) != -1) {
b.append((char) ch);
}
String s = b.toString();
Log.i("Response", s);
dos.close();
}
错误包括
10-20 04:16:26.658:ERROR/dalvikvm heap(20213):8957952字节外部分配对于此进程太大。
10-20 04:16:26.658:错误/dalvikvm(20213):内存不足:堆大小=4551KB,已分配=3039KB,位图大小=9496KB
10-20 04:16:26.658:错误/(20213):虚拟机不允许我们分配8957952字节