解析java.lang.outofmemoryerror,导致一半文件上传到服务器

时间:2014-08-13 07:02:01

标签: java android httpurlconnection fileinputstream dataoutputstream

我正在尝试将大型视频文件上传到服务器。我写了一段适用于图像的代码,所以我认为我也应该为视频工作。

我写了下面的代码。

public int uploadFile(String sourceFileUri) {


    String fileName = sourceFileUri;
    //Log.v("ONMESSAGE", "File type is " + filetype + "File name is " + fileName);
    HttpURLConnection conn = null;
    DataOutputStream dos = null; 
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File sourceFile = new File(sourceFileUri);

    if (!sourceFile.isFile()) {             
         dialog.dismiss();         
         runOnUiThread(new Runnable() {
             public void run() {
                Toast.makeText(GcmActivity.this, "File not found", Toast.LENGTH_LONG).show();
             }
         });

         return 0;

    }
    else
    {
         try {                 
               // open a URL connection to the Servlet
             FileInputStream fileInputStream = new FileInputStream(sourceFile);
             URL url = new URL("http://example.com/ccs-business/upload.php");
             conn = (HttpURLConnection) url.openConnection();
             conn.setDoInput(true); 
             conn.setDoOutput(true); 
             conn.setUseCaches(false); 
             conn.setRequestMethod("POST");
             conn.setRequestProperty("Connection", "Keep-Alive");
             conn.setRequestProperty("ENCTYPE", "multipart/form-data");
             conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);                 
             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("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + fileName +"\"" + lineEnd);
             dos.writeBytes(lineEnd);
             bytesAvailable = fileInputStream.available();

             bufferSize = Math.min(bytesAvailable, maxBufferSize);//1
             buffer = new byte[bufferSize];//2
             bytesRead = fileInputStream.read(buffer, 0, bufferSize); //3

             while (bytesRead > 0) {    //4                  
               dos.write(buffer, 0, bufferSize);//5
               bytesAvailable = fileInputStream.available();//6
               bufferSize = Math.min(bytesAvailable, maxBufferSize);//7
               bytesRead = fileInputStream.read(buffer, 0, bufferSize);//8 

              }//9

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

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

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

             if(serverResponseCode == 200){

                 runOnUiThread(new Runnable() {
                      public void run() {                             

                          Toast.makeText(GcmActivity.this, "File Upload Complete.",
                                       Toast.LENGTH_SHORT).show();
                          dialog.dismiss();
                      }
                  });               
             }   
             fileInputStream.close();
             dos.flush();
             dos.close();

        } catch (MalformedURLException ex) {

            dialog.dismiss(); 
            ex.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(GcmActivity.this, "MalformedURLException",
                                                        Toast.LENGTH_SHORT).show();
                }
            });

            Log.v("ONMESSAGE", "error: " + ex.getMessage(), ex); 
        } catch (Exception e) {

            dialog.dismiss(); 
            e.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {

                    Toast.makeText(GcmActivity.this, "Got Exception : see logcat ",
                            Toast.LENGTH_SHORT).show();
                }
            });
            Log.v("ONMESSAGE", "Exception : "
                                             + e.getMessage(), e); 
        }
        dialog.dismiss();      
        return serverResponseCode;

     } // End else block
   }

这段代码给了我 java.lang.OutOfMemory 错误,所以我按照其他人的建议添加了一个显示 largeheap 的密钥,没有工作。所以我遵循其他建议并将代码更改为

public int uploadFileVideo(String sourceFileUri) {


    String fileName = sourceFileUri;
    //Log.v("ONMESSAGE", "File type is " + filetype + "File name is " + fileName);
    HttpURLConnection conn = null;
    DataOutputStream dos = null; 
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File sourceFile = new File(sourceFileUri);

    if (!sourceFile.isFile()) {             
         dialog.dismiss();         
         runOnUiThread(new Runnable() {
             public void run() {
                Toast.makeText(GcmActivity.this, "File not found", Toast.LENGTH_LONG).show();
             }
         });

         return 0;

    }
    else
    {
         try {                 
               // open a URL connection to the Servlet
             FileInputStream fileInputStream = new FileInputStream(sourceFile);
             URL url = new URL("http://example.com/ccs-business/upload.php");
             conn = (HttpURLConnection) url.openConnection();
             conn.setDoInput(true); 
             conn.setDoOutput(true); 
             conn.setUseCaches(false); 
             conn.setRequestMethod("POST");
             conn.setRequestProperty("Connection", "Keep-Alive");
             conn.setRequestProperty("ENCTYPE", "multipart/form-data");
             conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);                 
             conn.setRequestProperty("uploaded_video", 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("Content-Disposition: form-data; name=\"uploaded_video\";filename=\"" + fileName +"\"" + lineEnd);
             dos.writeBytes(lineEnd);
             bytesAvailable = fileInputStream.available();

            /* bufferSize = Math.min(bytesAvailable, maxBufferSize);
             buffer = new byte[bufferSize];
             bytesRead = fileInputStream.read(buffer, 0, bufferSize); */



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

             fileInputStream.read(byt);

             bytesRead = fileInputStream.read(buffer, 0, bufferSize);

             dos.write(buffer, 0, bufferSize);



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

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

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

             if(serverResponseCode == 200){

                 runOnUiThread(new Runnable() {
                      public void run() {                             

                          Toast.makeText(GcmActivity.this, "File Upload Complete.",
                                       Toast.LENGTH_SHORT).show();
                          dialog.dismiss();
                      }
                  });               
             }   
             fileInputStream.close();
             dos.flush();
             dos.close();

        } catch (MalformedURLException ex) {

            dialog.dismiss(); 
            ex.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(GcmActivity.this, "MalformedURLException",
                                                        Toast.LENGTH_SHORT).show();
                }
            });

            Log.v("ONMESSAGE", "error: " + ex.getMessage(), ex); 
        } catch (Exception e) {

            dialog.dismiss(); 
            e.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {

                    Toast.makeText(GcmActivity.this, "Got Exception : see logcat ",
                            Toast.LENGTH_SHORT).show();
                }
            });
            Log.v("ONMESSAGE", "Exception : "
                                             + e.getMessage(), e); 
        }
        dialog.dismiss();      
        return serverResponseCode;

     } // End else block
   }

现在文件已上传,但所有文件大小均为1 MB且无法播放。

2 个答案:

答案 0 :(得分:0)

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

fileInputStream.read(byt);

您不是将读取的字节写入输出流。删除第一个读入byt应解决问题。但是你会遇到另一个问题,即1MB以上的文件只会上传1MB。

复制流的正确方法是执行与

类似的操作
byte[] buf = new byte[ 1024 ];
int read = 0;
while( ( read = in.read( buf ) ) != -1 ) {
    out.write( buf, 0, read );
}

答案 1 :(得分:0)

通过在conn.setChunkedStreamingMode(0);之后添加con.setDoOutput(true);来避免在RAM中缓冲整个POST数据 希望这个帮助:)