在Android中上传大文件而不会出现内存错误

我的上传代码如下:


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,但它上传成功。但是当它超过16 mb时,“OutOfMemory”错误显示出来。如何避免outofmemory错误?


三国纷争
浏览 583回答 3
3回答

莫回无

如果服务器接受分块模式,则可以使用((HttpURLConnection) con).setChunkedStreamingMode(chunkLength)否则你可以使用((HttpURLConnection) con).setChunkedStreamingMode(0);要么/* compute first your request content length   contentLength = formBodyLength + yourFileSize*/con.setRequestProperty("Content-Length", String.valueOf(contentLength));((HttpURLConnection) con).setFixedLengthStreamingMode(contentLength);终于......发送你想要的东西

慕的地10843

bitmap=Bitmap.createScaledBitmap(bitmap, 100, 100, true);ByteArrayOutputStream stream = new ByteArrayOutputStream();bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); //compress to format you want.byte [] byte_arr = stream.toByteArray();  String image_str = Base64.encodeBytes(byte_arr);最好的方式我试过它对我来说是成功的!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Android