2014-11-04 72 views
0

我試圖使用HttpClient發佈媒體文件到服務器。我的代碼適用於圖像文件,但無法重播視頻文件(mp4)。我張貼的文件代碼:使用HttpClient發佈Base64編碼的視頻文件

HttpClient httpclient = new DefaultHttpClient(); 
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); 

    HttpPost httppost = new HttpPost(REMOTE + "/add_file.php"); 

    MultipartEntityBuilder mpEntity = MultipartEntityBuilder.create(); 
    ContentBody cbFile = null; 
    String mimeType = ""; 
    if (file.getName().endsWith(".jpg") || file.getName().endsWith(".jpeg")) { 
     mimeType = "image/jpeg"; 
    } else if (file.getName().endsWith(".mp4")) { 
     mimeType = "video/mp4"; 
    } 


    mpEntity.addTextBody("recipient_phone", recipientPhoneStr); 
    mpEntity.addTextBody("sender_phone", "55000"); 
    mpEntity.addTextBody("sender_key", "my_secret"); 
    mpEntity.addTextBody("file_name", file.getName()); 

    mpEntity.addTextBody("userfile", encodeFileToBase64Binary(file)); 

    httppost.setEntity(mpEntity.build()); 

    HttpResponse response = httpclient.execute(httppost); 
    HttpEntity resEntity = response.getEntity(); 


    if (response.getStatusLine().toString().compareTo(HTTP_ERROR) == 0) { 
     throw new IOException(HTTP_ERROR); 
    } 

    if (resEntity != null) { 
     System.out.println(EntityUtils.toString(resEntity)); 
    } 
    if (resEntity != null) { 
     resEntity.consumeContent(); 
    } 

    httpclient.getConnectionManager().shutdown(); 

的文件是使用Base64.encodeBase64String(字節)base64編碼;

+0

你是否檢查過你收到所有字節?你可能會碰到php的post_max_size或apache/nginx限制。 – bart 2014-11-04 21:20:30

+0

謝謝你。是的,post_max_size是足夠的...我如何檢查Apache的限制? – JB2 2014-11-04 23:01:11

+0

將文件映射到字節並將緩衝區包裝在POST的'byteArrayEntity'中。 – 2014-11-05 00:56:56

回答

1

https://hc.apache.org/httpcomponents-client-4.3.x/examples.html

檢查從樣本POST程序...

使用下面的映射一個MP4到字節,然後把它包裝在適當的「實體」類型用於執行POST ..

  FileInputStream fis = new FileInputStream(mfile); 
      FileChannel fc = fis.getChannel(); // Get the file's size and then map it into memory 
      int sz = (int)fc.size(); 
      MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz); 
      byte[] data2 = new byte[bb.remaining()]; 
      bb.get(data2); 
      ByteArrayEntityHC4 reqEntity = new ByteArrayEntityHC4(data2); 
      httpPost.setEntity(reqEntity); 
      fis.close(); 

然後調用exec類型的POST請求。