Android:上传大文件时的outofmemory

时间:2016-04-12 13:07:48

标签: java android http httpurlconnection

我正在上传一个大文件 - 几百mbs ..这个过程大约一半然后崩溃

04-12 09:01:02.407 6862-7067/com.sm.trackit W/art: Throwing OutOfMemoryError "Failed to allocate a 28 byte allocation with 3952 free bytes and 3KB until OOM" (recursive case)
04-12 09:01:02.407 6862-7067/com.sm.trackit W/art: "Thread-151" prio=5 tid=14 Runnable
04-12 09:01:02.408 6862-7067/com.sm.trackit W/art:   | group="main" sCount=0 dsCount=0 obj=0x1ac094c0 self=0xa3b63800
04-12 09:01:02.408 6862-7067/com.sm.trackit W/art:   | sysTid=7067 nice=0 cgrp=default sched=0/0 handle=0xa1e71930
04-12 09:01:02.408 6862-7067/com.sm.trackit W/art:   | state=R schedstat=( 0 0 0 ) utm=1336 stm=492 core=0 HZ=100
04-12 09:01:02.408 6862-7067/com.sm.trackit W/art:   | stack=0xa1d6f000-0xa1d71000 stackSize=1038KB
04-12 09:01:02.408 6862-7067/com.sm.trackit W/art:   | held mutexes= "mutator lock"(shared held)
04-12 09:01:02.408 6862-7067/com.sm.trackit W/art:     at libcore.io.IoBridge.available(IoBridge.java:57)
04-12 09:01:02.408 6862-7067/com.sm.trackit W/art:     at java.io.FileInputStream.available(FileInputStream.java:108)
04-12 09:01:02.408 6862-7067/com.sm.trackit W/art:     at com.sm.trackit.DatabaseHandler.uploadFile(DatabaseHandler.java:209)
04-12 09:01:02.408 6862-7067/com.sm.trackit W/art:     at com.sm.trackit.MainActivity$75$1.run(MainActivity.java:5476)
04-12 09:01:02.408 6862-7067/com.sm.trackit W/art:     at java.lang.Thread.run(Thread.java:818)





HttpURLConnection conn = null;
    DataOutputStream dos = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "**345698754r2398&&+*&38*&^+*********";
    byte[] buffer;
    int maxBufferSize = 1024;////1 * 1024 * 1024;


try {

        // open a URL connection to the Servlet
        FileInputStream fileInputStream = new FileInputStream(sourceFile);
        URL url = new URL(upLoadServerUri);

        // Open a HTTP  connection to  the URL
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true); // Allow Inputs
        conn.setDoOutput(true); // Allow Outputs
        conn.setUseCaches(false); // Don't use a Cached Copy
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        String contentlength = toString().valueOf(sourceFile.length());
    //  conn.setRequestProperty("Content-Length", contentlength);

        conn.setRequestProperty("uploaded_file", fileName);

        dos = new DataOutputStream(conn.getOutputStream());

        dos.writeBytes(twoHyphens + boundary + lineEnd);

        dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                        + fileName + "\"" + lineEnd);

                dos.writeBytes(lineEnd);

        // create a buffer of  maximum size
        bytesAvailable = fileInputStream.available(); 

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

        // read file and write it into form...
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        percantcounterFinal = bytesAvailable;
        percantcounter = 0;

        while (bytesRead > 0) {
            percantcounter += bytesRead;
            MA.runOnUiThread(new Runnable() {
                public void run() {
                    float per = percantcounter / percantcounterFinal;
                    per *= 100;
                    MA.pb.setProgress((int) per);
                    Log.i("TAG", "perc:" + String.valueOf(percantcounter) +  "percentage" + toString().valueOf(per) + " counter:" + String.valueOf(percantcounterFinal));
                }
            });
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available(); //THIS IS EXCEPTION LOCATION
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        // send multipart form data necesssary after file data...
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);



        MA.runOnUiThread(new Runnable() {
            public void run() {
                MA.pb.setProgress(80);
                MA.cur_val.setText("Waiting for Response...");
            }
        });

        // Responses from the server (code and message)
         serverResponseCode = conn.getResponseCode();
        final String serverResponseMessage = conn.getResponseMessage();

        Log.i("uploadFile", "HTTP Response is : "
                + serverResponseMessage + ": " + serverResponseCode);

        if(serverResponseCode == 200){

            MA.runOnUiThread(new Runnable() {
                public void run() {
                    MA.diagFile.dismiss();
                    String msg = serverResponseMessage + "\n\n"
                            +" http://www.gotrashpad.com/test/"
                            +fileName;
                    MA.cur_val.setText("Finished");
                    Toast.makeText(MainActivity.m_this, "File Upload Complete.",
                            Toast.LENGTH_SHORT).show();


            }
            });
        }

        //close the streams //
        fileInputStream.close();
        dos.flush();
        dos.close();
        sourceFile.delete();

    } 

0 个答案:

没有答案