2017-01-24 93 views
1

我知道我的問題已經解決已經多次,但我無法找到任何東西,這將有助於我與我的具體問題。採摘文件(URI到文件路徑)

我有一個意圖從系統中選擇一個文件的任何地方:

private void showFileChooser() { 
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
    intent.setType("*/*"); 
    intent.addCategory(Intent.CATEGORY_OPENABLE); 

    try { 
     startActivityForResult(
       Intent.createChooser(intent, "Select a File to Upload"), 
       FILE_SELECT_CODE); 
    } catch (android.content.ActivityNotFoundException ex) { 
     // Potentially direct the user to the Market with a Dialog 
     Toast.makeText(this, "Please install a File Manager.", 
       Toast.LENGTH_SHORT).show(); 
    } 


} 

我撿起這個意圖在這裏:

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 

    switch (requestCode) { 
     case FILE_SELECT_CODE: 

      if (resultCode == RESULT_OK) { 
       // Get the Uri of the selected file 
       Uri uri = data.getData(); 

}

和我有一個上傳方法類似所以:

private void upload(File file){ 
    RequestParams params = new RequestParams(); 
    try { 
     params.put("fileToUpload", file); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } 
    AsyncHttpClient client = new AsyncHttpClient(); 
    client.post("http://...", params, new AsyncHttpResponseHandler() { 

     @Override 
     public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { 
      System.out.println("statusCode "+statusCode);//statusCode 200 
     } 

     @Override 
     public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { 

     } 
    }); 
} 

的問題是,我不知道如何「嫁」兩種方法onActivity和上傳,因爲我不知道如何處理從我的意圖得到的信息,以便AsyncHttpClient可以使用它。

我試圖轉換的URI的絕對路徑,但無法管理(解決方案網上說似乎工作,其中專門爲圖像)。我也不能將uri「轉換」爲一個文件。

無論如何,我能做到這一點?我錯過了什麼嗎?

回答

3

理想的解決方案是使用ContentResolveropenInputStream()獲得由Uri標識內容的InputStream,然後傳遞到InputStream在上傳使用您的HTTP客戶端API。

如果你的HTTP客戶端API不支持使用InputStream或東西,可以從一個(例如,Reader)導出,所以你需要一個File,使用InputStream和一些文件FileOutputStream您控制到製作內容的本地副本(例如,在getCacheDir()中)。然後,使用本地副本進行文件上載操作,並在完成後刪除本地副本。

+0

是的,謝謝你,異步HTTP允許輸入流,而不是一個文件。 – hachel