2013-04-12 39 views
-1

我的應用程序要求用戶選擇一個上傳到PHP腳本的文件。當用戶選擇一個文件時,返回正確的URI,但是當我嘗試訪問該文件時,出現FileNotFound錯誤。以下是onActivityResult代碼:在Android中讀取文件和遠程上傳時出錯

private static final int FILE_SELECT_CODE = 1234;  
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(); 

       Log.d("file upload register page", "File Uri: " + uri.toString()); 
       try { 
       file_path = FileUtils.getPath(getBaseContext(), uri); 
      } 
       catch (URISyntaxException e) { 
       e.printStackTrace(); 
      } 
      Log.d("file upload register page", "File Path: " + file_path); 
      file = new File(file_path); 
      UploadFile task = new UploadFile(); 
      task.execute(); 
     }   
     break; 
    } 
super.onActivityResult(requestCode, resultCode, data); 
} 

Fileetils.getPath函數返回給定URI的路徑。根據日誌,我返回的路徑是: file:///mnt/sdcard/bluetooth/Tutorial%201.pdf

在AsyncTask UploadFile中,我將文件上傳到遠程服務器。我得到一個錯誤

java.io.FileNotFoundException: /file:/mnt/sdcard/bluetooth/Tutorial%201.pdf (No such file or directory). 

這是我上傳的文件:

public void newUpload() 
{ 
    HttpEntity resEntity; 
    try { 
     HttpClient httpclient = new DefaultHttpClient(); 

     HttpPost httppost = new HttpPost(url); 

     InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1); 
     reqEntity.setContentType("binary/octet-stream"); 
     reqEntity.setChunked(true); // Send in multiple parts if needed 
     httppost.setEntity(reqEntity); 
     HttpResponse response_http = httpclient.execute(httppost); 
     //Do something with response... 
     resEntity = response_http.getEntity(); 
     response = EntityUtils.toString(resEntity); 
     Log.d("response",response); 
    } 
    catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

如何解決未發現異常文件?我不知道爲什麼它不工作!

+1

當你做'新的FileInputStream(文件)','文件'的確切值是什麼?我不認爲'/ file:/ mnt/sdcard/bluetooth/Tutorial%201.pdf'應該有一個前導'/'' –

回答

2

檢查您的getPath()功能。它可能不會爲給定的URI發送正確的路徑。

+0

你是對的。問題出在getPath()函數本身。 – shiladitya