2012-03-09 32 views
20

đang tải lên của tôi như sau:Upload file lớn trong Android mà không có lỗi OutOfMemory

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

Trong khi nhỏ hơn 16 mb, nó tải lên thành công. Nhưng trong khi nó hơn 16 mb, lỗi "OutOfMemory" hiển thị. Làm thế nào để tránh lỗi outofmemory?

+0

Tôi muốn gửi 1024 byte mỗi lần trong khi ((length = fStream.read (buffer))! = -1) vòng lặp, nhưng tôi không biết cách thực hiện. – brian

+0

brian, vui lòng tham khảo câu trả lời của tôi ở đây: http://stackoverflow.com/questions/4455006/posting-a-large-file-in-android –

+0

hey @ Brian, bạn có thể gửi mã phía máy chủ –

Trả lời

64

Bạn có thử sử dụng

con.setChunkedStreamingMode(1024); 

Điều này sẽ giúp bạn đoạn dữ liệu của bạn vào kích thước cụ thể, do đó bạn không cần phải giữ toàn bộ tập tin của bạn trong bộ nhớ.

UPDATE:

Hãy thử sử dụng các phương pháp dưới đây. Tôi sử dụng phương pháp này để tải lên một tệp 80 mb mà không có Ngoại lệ.

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; 
} 
+0

đâu nên dòng thêm? – brian

+0

Tôi thử thêm vào bên dưới dòng con.setRequestProperty ("Content-Type", "multipart/form-data; boundary =" + boundary) ;, nhưng nó tải lên không thành công cho tất cả các tệp. – brian

+1

Lỗi java.io.FileNotFoundException: http: //ip/web/jquery/uploader/uploadify.php được hiển thị. – brian

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

cách tốt nhất tôi đã cố gắng nó đã thành công đối với tôi !!!

+0

liên kết đến phương pháp nén: https://developer.android.com/reference/android/graphics/Bitmap.html – chance

Các vấn đề liên quan