2012-04-14 49 views
7

Sự cố:tải video lên facebook trong android

Video của tôi không được tải lên Facebook.

Câu hỏi:

Làm thế nào tôi có thể upload video lên Facebook?

Note:

tôi có thể tải lên một hình ảnh từ bộ sưu tập của tôi.

Không có Exceptions bị ném. Tôi nghĩ có một vấn đề trong dòng

params.putString("filename", <selectedviedoPath>)

AsyncFacebookRunner mAsyncFbRunner = new AsyncFacebookRunner(mFacebook); 
     Bundle params = new Bundle(); 
     //convert to byte stream 
    **FileInputStream is = new FileInputStream(new File(selectedviedoPath));** 
    ByteArrayOutputStream bs = new ByteArrayOutputStream(); 
     int data = 0; 
     while((data = is.read()) != -1) 
     bs.write(data); 

     is.close(); 
     byte[] raw = bs.toByteArray(); 
     bs.close(); 

     params.putByteArray("video", raw); 
     params.putString("filename", <selectedviedoPath>); 
     mAsyncFbRunner.request("me/videos", params, "POST", new WallPostListener()); 
+1

Check-out http://stackoverflow.com/q/6908413/664479 –

+1

@anoop: bạn đã có câu trả lời hay không? Vui lòng chấp nhận đúng. Vì vậy, nó có thể giúp khác cũng có. –

Trả lời

5

Dưới đây là những gì tôi đã làm và bây giờ Hoạt động hoàn hảo để đăng video trên Facebook.

FacebookVideoPostActivity.java

public class FacebookVideoPostActivity extends Activity { 
/** Called when the activity is first created. */ 

private static Facebook facebook = new Facebook("YOUR_APP_ID"); // App ID For the App 
private String permissions[] = {""}; 
private String statusString = ""; 
private Button btn1; 
private String PATH = "/sdcard/test1.3gp"; // Put Your Video Link Here 
private ProgressDialog mDialog ; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    btn1 = (Button) findViewById(R.id.button1); 
    mDialog = new ProgressDialog(FacebookVideoPostActivity.this); 
    mDialog.setMessage("Posting video..."); 

    btn1.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      facebook.authorize(FacebookVideoPostActivity.this, new String[]{ "user_photos,publish_checkins,publish_actions,publish_stream"},new DialogListener() {      
       @Override      
       public void onComplete(Bundle values) { 
        postVideoonWall(); 

       }      
       @Override      
       public void onFacebookError(FacebookError error) {}      
       @Override      
       public void onError(DialogError e) {}      
       @Override      
       public void onCancel() {}     
      }); 

     } 
    }); 
} 

public void postVideoonWall() { 
    mDialog.setMessage("Posting ..."); 
    mDialog.show(); 
    new Thread(new Runnable() { 
     @Override 
     public void run() { 

      byte[] data = null; 
      InputStream is = null; 
      String dataMsg = "This video is posted from bla bla bla App"; 
      Bundle param; 

      try { 
       is = new FileInputStream(PATH); 
       data = readBytes(is); 
       param = new Bundle(); 
       param.putString("message", dataMsg); 
       param.putString("filename", "test1.mp4"); 
       //param.putString("method", "video.upload"); 
       param.putByteArray("video", data); 
       AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook); 
       mAsyncRunner.request("me/videos", param, "POST", new SampleUploadListener(), null); 
      } 
      catch (FileNotFoundException e) { 
       e.printStackTrace(); 
      } 
      catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    }).start(); 

} 


private Handler mPostHandler = new Handler() { 
    @Override 
    public void handleMessage(Message msg) { 
     mDialog.dismiss(); 
     if(msg.what==0){ 
      Toast.makeText(getApplicationContext(), "Image Posted on Facebook.", Toast.LENGTH_SHORT).show(); 
     } 
     else if(msg.what==1) { 
      Toast.makeText(getApplicationContext(), "Responce error.", Toast.LENGTH_SHORT).show(); 
     }else if(msg.what==2){ 
      Toast.makeText(getApplicationContext(), "Facebook error.", Toast.LENGTH_SHORT).show(); 
     } 
    } 
}; 



public byte[] readBytes(InputStream inputStream) throws IOException { 
    // This dynamically extends to take the bytes you read. 
    ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(); 

    // This is storage overwritten on each iteration with bytes. 
    int bufferSize = 1024; 
    byte[] buffer = new byte[bufferSize]; 

    // We need to know how may bytes were read to write them to the byteBuffer. 
    int len = 0; 
    while ((len = inputStream.read(buffer)) != -1) { 
     byteBuffer.write(buffer, 0, len); 
    } 

    // And then we can return your byte array. 
    return byteBuffer.toByteArray(); 
} 

public class SampleUploadListener extends BaseRequestListener { 
    public void onComplete(final String response, final Object state) { 
     try {    
      Log.d("Facebook-Example", "Response: " + response.toString());    
      JSONObject json = Util.parseJson(response);    
      mPostHandler.sendEmptyMessage(0); 
      // then post the processed result back to the UI thread    
      // if we do not do this, an runtime exception will be generated    
      // e.g. "CalledFromWrongThreadException: Only the original    
      // thread that created a view hierarchy can touch its views."   
     } catch (JSONException e) {    
      mPostHandler.sendEmptyMessage(1); 
      Log.w("Facebook-Example", "JSON Error in response");   
     } catch (FacebookError e) { 
      mPostHandler.sendEmptyMessage(2); 
      Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());   
     }  
    }  
    @Override  
    public void onFacebookError(FacebookError e, Object state) {   
     // TODO Auto-generated method stub  
    } 
} 

}

Bây giờ, Tích hợp Facebook SDK trong dự án của bạn và làm thay đổi như sau:

Thay đổi Util.java từ facebook sdk như sau

public static String openUrl(String url, String method, Bundle params) 
      throws MalformedURLException, IOException { 
     // random string as boundary for multi-part http post 
     String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f"; 
     String endLine = "\r\n"; 

     OutputStream os; 



// ADDED By Shreyash For Publish Video 
// [email protected] 
// Mo. 919825056129 
     // Try to get filename key 
      String filename = params.getString("filename"); 
      // If found 
      if (filename != null) { 
       // Remove from params 
       params.remove("filename"); 
      } 
//=================================================== 


     if (method.equals("GET")) { 
      url = url + "?" + encodeUrl(params); 
     } 
     Util.logd("Facebook-Util", method + " URL: " + url); 
     HttpURLConnection conn = 
      (HttpURLConnection) new URL(url).openConnection(); 
     conn.setRequestProperty("User-Agent", System.getProperties(). 
       getProperty("http.agent") + " FacebookAndroidSDK"); 
     if (!method.equals("GET")) { 
      Bundle dataparams = new Bundle(); 
      for (String key : params.keySet()) { 
       Object parameter = params.get(key); 
       if (parameter instanceof byte[]) { 
        dataparams.putByteArray(key, (byte[])parameter); 
       } 
      } 

      // use method override 
      if (!params.containsKey("method")) { 
       params.putString("method", method); 
      } 

      if (params.containsKey("access_token")) { 
       String decoded_token = 
        URLDecoder.decode(params.getString("access_token")); 
       params.putString("access_token", decoded_token); 
      } 

      conn.setRequestMethod("POST"); 
      conn.setRequestProperty(
        "Content-Type", 
        "multipart/form-data;boundary="+strBoundary); 
      conn.setDoOutput(true); 
      conn.setDoInput(true); 
      conn.setRequestProperty("Connection", "Keep-Alive"); 
      conn.connect(); 
      os = new BufferedOutputStream(conn.getOutputStream()); 

      os.write(("--" + strBoundary +endLine).getBytes()); 
      os.write((encodePostBody(params, strBoundary)).getBytes()); 
      os.write((endLine + "--" + strBoundary + endLine).getBytes()); 

      if (!dataparams.isEmpty()) { 

       for (String key: dataparams.keySet()){ 
    // ADDED By Shreyash For Publish Video 
// [email protected]ail.com 
// Mo. 919825056129 
// os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes()); 
        os.write(("Content-Disposition: form-data; filename=\"" + ((filename) != null ? filename : key) + "\"" + endLine).getBytes()); 
        os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes()); 
        os.write(dataparams.getByteArray(key)); 
        os.write((endLine + "--" + strBoundary + endLine).getBytes()); 

       } 
      } 
      os.flush(); 
     } 

     String response = ""; 
     try { 
      response = read(conn.getInputStream()); 
     } catch (FileNotFoundException e) { 
      // Error Stream contains JSON that we can parse to a FB error 
      response = read(conn.getErrorStream()); 
     } 
     return response; 
    } 

Đặt hàm trên vào Util.Java đó và nhận xét cùng hàm có sẵn trong đó.

Bây giờ hãy chạy dự án. Nếu có bất kỳ truy vấn nào thì hãy cho tôi biết.

Enjoy :)

+0

Bạn đã có giải pháp chưa? –

+0

tôi chỉ có thể tải lên video 3gp ... bạn có thể tải lên mp4 hoặc bất kỳ video nào khác không? –

+0

@SanketKachhela: Bạn đã thấy mã của tôi trong câu trả lời chưa? Tôi cũng có thể tải lên video mp4. Nó là video ở định dạng mp4 sau đó nó sẽ mất thời gian để tải lên nó vì nó có kích thước lớn. Nhưng bạn chắc chắn sẽ nhận được nó vào bài tường trong một vài phút. –

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