为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

三国纷争 2019-09-02 08:34:04
我的上传代码如下: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错误?
查看完整描述

3 回答

?
莫回无

TA贡献1865条经验 获得超7个赞

如果服务器接受分块模式,则可以使用


((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);

终于......发送你想要的东西


查看完整回答
反对 回复 2019-09-02
?
慕的地10843

TA贡献1785条经验 获得超8个赞

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);

最好的方式我试过它对我来说是成功的!


查看完整回答
反对 回复 2019-09-02
  • 3 回答
  • 0 关注
  • 581 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信