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

标签 android upload out-of-memory httpurlconnection

我的上传代码如下:

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”错误显示。 如何避免内存不足错误?

最佳答案

你尝试过使用

con.setChunkedStreamingMode(1024);

这将帮助您将数据分 block 为特定大小,这样您就无需将整个文件保存在内存中。

更新:

尝试使用以下方法。我使用这种方法上传一个 80 mb 的文件,没有异常。

public String sendFileToServer(String filename, String targetUrl) {
    String response = "error";
    Log.e("Image filename", filename);
    Log.e("url", targetUrl);
    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    // DataInputStream inputStream = null;

    String pathToOurFile = filename;
    String urlServer = targetUrl;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    DateFormat df = new SimpleDateFormat("yyyy_MM_dd_HH:mm:ss");

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024;
    try {
        FileInputStream fileInputStream = new FileInputStream(new File(
                pathToOurFile));

        URL url = new URL(urlServer);
        connection = (HttpURLConnection) url.openConnection();

        // Allow Inputs & Outputs
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setChunkedStreamingMode(1024);
        // Enable POST method
        connection.setRequestMethod("POST");

        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Content-Type",
                "multipart/form-data;boundary=" + boundary);

        outputStream = new DataOutputStream(connection.getOutputStream());
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);

        String connstr = null;
        connstr = "Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
                + pathToOurFile + "\"" + lineEnd;
        Log.i("Connstr", connstr);

        outputStream.writeBytes(connstr);
        outputStream.writeBytes(lineEnd);

        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        // Read file
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        Log.e("Image length", bytesAvailable + "");
        try {
            while (bytesRead > 0) {
                try {
                    outputStream.write(buffer, 0, bufferSize);
                } catch (OutOfMemoryError e) {
                    e.printStackTrace();
                    response = "outofmemoryerror";
                    return response;
                }
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }
        } catch (Exception e) {
            e.printStackTrace();
            response = "error";
            return response;
        }
        outputStream.writeBytes(lineEnd);
        outputStream.writeBytes(twoHyphens + boundary + twoHyphens
                + lineEnd);

        // Responses from the server (code and message)
        int serverResponseCode = connection.getResponseCode();
        String serverResponseMessage = connection.getResponseMessage();
        Log.i("Server Response Code ", "" + serverResponseCode);
        Log.i("Server Response Message", serverResponseMessage);

        if (serverResponseCode == 200) {
            response = "true";
        }

        String CDate = null;
        Date serverTime = new Date(connection.getDate());
        try {
            CDate = df.format(serverTime);
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("Date Exception", e.getMessage() + " Parse Exception");
        }
        Log.i("Server Response Time", CDate + "");

        filename = CDate
                + filename.substring(filename.lastIndexOf("."),
                        filename.length());
        Log.i("File Name in Server : ", filename);

        fileInputStream.close();
        outputStream.flush();
        outputStream.close();
        outputStream = null;
    } catch (Exception ex) {
        // Exception handling
        response = "error";
        Log.e("Send file Exception", ex.getMessage() + "");
        ex.printStackTrace();
    }
    return response;
}

关于android - 在Android中上传大文件而不会出现内存不足错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9630430/

相关文章:

java - 我应该为我的 Android 应用程序使用 SQLite 数据库还是只使用 JSON?

c# - 内存流和大对象堆

java - OutOfMemory Exception - VisualVM 如何通过 heapdump 文件帮助定位内存泄漏?

android - Android 中类似 iPhone 的标签栏?

android - 使警报对话框背景透明

php - 通过PHP将文本,图像,整数发布到MySQL数据库

forms - 出于样式目的隐藏文件时,IE 无法发送文件上传

c# - 导致内存不足异常的大字符串数组 (C#)

android - Universal Image Loader 重用图像

php - 将图像附件添加到 PHP 消息?