2012-08-28 109 views
2

是否有任何使用NDK將文件從SD上傳到服務器的源代碼?或任何其他方法上傳一個大尺寸的文件沒有得到Android NDK:使用NDK上傳文件

Out Of Memory Exception 

如果是這樣,請給我提供鏈接?

下面的代碼是我使用的一個,我得到了內存溢出異常

private void UploadFileByClient(LocalFileVO localFileVO){ 


     try{ 

      File uploadFile = new File(
        (localFileVO.getFolderPath() + "/" + localFileVO.getFileName())); 

      HttpClient client = new DefaultHttpClient(); 

      final HttpResponse resp; 
      final HttpClient httpClient = new DefaultHttpClient(); 
      final HttpPut post = new HttpPut("https://qa2-talos-vip-mexico.symnds.com/fileservice/files/"); 
      post.setHeader("User-Agent", "Mexico/1.0.0.57/android"); 
      post.setHeader("Content-Type", localFileVO.getMimeType()); 
      post.setHeader("Authorization", TOKEN); 
      post.setHeader("x-mexico-endpointid", GUID); 
      post.setHeader("x-mexico-filehash", localFileVO.getFileHash()); 
      post.setHeader("x-mexico-filesize", localFileVO.getSize()); 

      if (!TextUtils.equals("0", localFileVO.getFolderId())) 
       post.setHeader("x-mexico-folder", localFileVO.getFolderId()); 

      post.setHeader("x-mexico-filename", localFileVO.getEncodedFileName()); 
      post.setHeader("Expect", "100-continue"); 
      post.setHeader("x-mexico-modtime", 
        String.valueOf(System.currentTimeMillis()/1000)); 



//   ParcelFileDescriptor fileDescriptor = this.getContentResolver().openFileDescriptor(Uri.parse(uploadFile.getAbsolutePath()), "r"); 
//   InputStream in = this.getContentResolver().openInputStream(Uri.parse(uploadFile.getAbsolutePath())); 
      InputStream in = new FileInputStream(uploadFile); 

      CountingInputStreamEntity entity = new CountingInputStreamEntity(in, uploadFile.length()); 
      entity.setUploadListener(this); 
      post.setEntity(entity); 
      resp = httpClient.execute(post); 
      if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { 
       System.out.println("=======================Got the response from server============================"); 
      } 


     }catch(Exception e){ 
      System.out.println("==============Failed using HttpClient================="+e.getMessage()); 
     } 

    } 

    private int uploadFile(LocalFileVO localFileVO) throws IOException { 


     UploadFileByClient(localFileVO); 

     if(true){ 
      return 0; 
     } 

     File uploadFile = new File((localFileVO.getFolderPath() + "/" + localFileVO.getFileName())); 


     System.setProperty("http.keepAlive", "false"); 

     int  code = 0; 
     try{ 

     HttpURLConnection urlConnection; 

     URL url = new URL("https://qa2-talos-vip-mexico.symnds.com/fileservice/files/"); 
    // URL url = new URL("https://zpi.nortonzone.com/fileservice/files/"); 

     urlConnection = (HttpURLConnection) url.openConnection(); 
     urlConnection.setConnectTimeout(30000); 
     urlConnection.setRequestProperty("Host", url.getHost()); 
     // urlConnection.setRequestProperty("Connection", "Keep-Alive"); 
     urlConnection.setDoInput(true); 
     urlConnection.setDoOutput(true); 
     urlConnection.setUseCaches(false); 
     urlConnection.setInstanceFollowRedirects(false); 
    // urlConnection.setChunkedStreamingMode(1024); 
     urlConnection.setFixedLengthStreamingMode(Integer.parseInt(localFileVO.getSize())); 
     //urlConnection.setChunkedStreamingMode(1024); 

     urlConnection.setRequestMethod("PUT"); 
     urlConnection.setRequestProperty("User-Agent", "Mexico/1.0.0.57/android"); 
     urlConnection.setRequestProperty("Content-Type", localFileVO.getMimeType()); 
     //urlConnection.setRequestProperty("Content-Length", localFileVO.getSize()); 
     urlConnection.setRequestProperty("Authorization", TOKEN); 
     urlConnection.setRequestProperty("x-mexico-endpointid", GUID); 
     urlConnection.setRequestProperty("x-mexico-filehash", localFileVO.getFileHash()); 
     //urlConnection.setRequestProperty("x-mexico-filesize", localFileVO.getSize()); 

     if (!TextUtils.equals("0", localFileVO.getFolderId())) 
      urlConnection.setRequestProperty("x-mexico-folder", localFileVO.getFolderId()); 

     urlConnection.setRequestProperty("x-mexico-filename", localFileVO.getEncodedFileName()); 
     urlConnection.setRequestProperty("Expect", "100-continue"); 
     urlConnection.setRequestProperty("x-mexico-modtime", 
       String.valueOf(System.currentTimeMillis()/1000)); 

     bufferOutputStream = new BufferedOutputStream(urlConnection.getOutputStream(),BSIZE); 
    // CountingOutputStream cOutStream = new CountingOutputStream(bufferOutputStream); 

     FileInputStream fileInputStream = new FileInputStream(uploadFile); 

     long startTime = System.currentTimeMillis(); 
     try{ 
      int totalSize = 0; 

      while (true) { 
        synchronized (chunks) { 
         int amountRead = fileInputStream.read(chunks); 
         System.out.println("========amount read========="+amountRead); 
         if (amountRead == -1) { 
           break; 
         } 
         bufferOutputStream.write(chunks, 0, amountRead); 
         bufferOutputStream.flush(); 
        } 
      } 
      System.out.println("================================TotalSize " + totalSize); 
      bufferOutputStream.flush(); 
      bufferOutputStream.close(); 
      fileInputStream.close(); 
      }catch(Exception e){ 
       e.printStackTrace(); 
      } 
     long endTime = System.currentTimeMillis(); 
     System.out.println("=============================================Writing time ==========================================================" + (endTime - startTime)); 
     //code = urlConnection.getResponseCode(); 

     InputStream inputStream = urlConnection.getInputStream(); 



    long endTime1 = System.currentTimeMillis(); 
    System.out.println("Time to get the response is " + (endTime1 - endTime)); 
    // progressBar.setProgress(100); 
     System.out.println("=================Response code is ================="+code); 
     urlConnection.disconnect(); 
     //fileInputStream.close(); 

     }catch(Exception e){ 
      System.out.println("========================Exception occured=================="+e.getMessage()); 
     } 
     return code; 

    } 

感謝ü

+1

而且,你到目前爲止嘗試過了什麼? – Lucifer

+0

我試過使用SDK ie Fileinputstream和bufferedoutputstream來讀寫。使用這個只有我得到了** OUT OF MEMORY EXCEPTION **(試圖上傳20MB zip文件) – Sudarshan

+0

好,您應該上傳該代碼,以便我們可以幫助您更好的親愛的:) – Lucifer

回答

0

你不需要NDK這一點。如果沒有你的代碼,我只能建議將整個文件讀入緩衝區。這是錯誤的。這樣做: 閱讀小零件文件和發送這些部件逐個放入輸出流(從連接得到它)

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

// 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()); 
.... 
// Read file 
bytesRead = fileInputStream.read(buffer, 0, bufferSize); 

while (bytesRead > 0) 
{ 
outputStream.write(buffer, 0, bufferSize); 
bytesAvailable = fileInputStream.available(); 
bufferSize = Math.min(bytesAvailable, maxBufferSize); 
bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
} 

outputStream.writeBytes(lineEnd); 
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); 

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

fileInputStream.close(); 
outputStream.flush(); 
outputStream.close(); 
+0

我編輯我的問題的代碼 – Sudarshan

+0

先生,我有一個懷疑..這段代碼不會顯示任何**內存異常?** bcoz iam試圖上傳一個非常大的文件的大小最小20 MB - 最大150 MB – Sudarshan

+0

我在這裏沒有工作示例,但基於此方法的應用程序可以正常上傳視頻文件。如果我沒有記錯的話,它前段時間使用了google搜索,我在這裏重新找到這個示例http://www.coderzheaven.com/2012/03/29/uploading-audio-video-or-image-files-from-android- to-server/ –

0

看來你錯過了setChunkedStreamingMode(INT)調用 :HTTP://開發商。 android.com/reference/java/net/HttpURLConnection.html 發佈內容 要將數據上傳到Web服務器,請使用setDoOutput(true)配置輸出連接。 爲了獲得最佳性能,您應該在預先知道主體長度時調用setFixedLengthStreamingMode(int),否則在setChunkedStreamingMode(int)時調用它。否則HttpURLConnection將被強制緩衝完整的請求主體在內存之前它被傳輸,浪費(可能耗盡)堆並增加延遲。

但是您的內容太大而無法緩衝。

+0

先生我無法理解術語**體長**(當身體的長度是已知的提前)..是你指定文件的大小 – Sudarshan

+0

先生,我試過setChunkedStreamingMode(1000 * 1024),但仍然是相同的錯誤。 – Sudarshan