2016-07-14 40 views
2

我試圖通過本地文件方式上傳圖片。上傳圖片時發生Android FireBase錯誤

UploadTask uploadTask = currentPicRef.putFile(file, metadata); 

當用戶從圖庫中挑選圖像或通過相機拍照時,圖片保存在外部存儲器中,我保存共享首選項中的uri。

我成功加載圖像到一個ImageView的使用setImageURI(uri)方法,但是當我打電話的火力點方法,並使用相同的URI(Uri file = Uri.fromFile(new File(fileName));
我得到的錯誤

無法定位上傳文件:文件:///含量%3A /媒體/外部/圖像/媒體/ 22943

,但是當我使用日誌檢查本地文件,我得到

URI是內容://媒體/外部/圖像/媒體/ 22943

還值得一提的是,當我用uri.parse()的火力點,而不是uri.fromFile()從本地文件上傳上傳的元數據,但不照片本身。

任何想法如何解決它?

回答

2

也許這是一個有點晚了,反正:

無法定位上傳文件:文件:///含量%3A /媒體/外部/圖像/媒體/ 22943

我認爲你可能有一個URL編碼的問題(見文件uri中的%3A)。

嘗試在將其傳遞給Firebase存儲參考之前先解碼uri Uri file = Uri.fromFile(new File(fileName));

如果它不起作用,取而代之的是以這種方式檢索圖像uri Uri.fromFile(new File(fileName)),您可以嘗試在共享偏好設置中保存本地圖像路徑(我假設當您從圖庫或相機中獲取圖像時,也可以有本地路徑),並使用它在存儲Firebase中上傳圖像。

希望能有所幫助。

0

fileName可以確定fileUri.toString()。這爲我工作:

Uri uploadUri = Uri.fromFile(new File(fileUri.toString())); 

這裏有一個工作的例子:

// [START upload_from_uri] 
private void uploadFromUri(Uri fileUri) { 

    Uri uploadUri = Uri.fromFile(new File(fileUri.toString())); 

    Log.d(TAG, "uploadFromUri:src:" + fileUri.toString()); 

    // [START get_child_ref] 
    // Get a reference to store file at photos/<FILENAME>.jpg 
    final StorageReference photoRef = mStorageRef.child("photos").child(uploadUri.getLastPathSegment()); 
    // [END get_child_ref] 

    // Upload file to Firebase Storage 
    // [START_EXCLUDE] 
    showProgressDialog(); 
    // [END_EXCLUDE] 
    Log.d(TAG, "uploadFromUri:dst:" + photoRef.getPath()); 

    photoRef.putFile(uploadUri) 
      .addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() { 
       @Override 
       public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { 
        // Upload succeeded 
        Log.d(TAG, "uploadFromUri:onSuccess"); 

        // Get the public download URL 
        mDownloadUrl = taskSnapshot.getMetadata().getDownloadUrl(); 

        // [START_EXCLUDE] 
        hideProgressDialog(); 
        updateUI(mAuth.getCurrentUser()); 
        // [END_EXCLUDE] 
       } 
      }) 
      .addOnFailureListener(this, new OnFailureListener() { 
       @Override 
       public void onFailure(@NonNull Exception exception) { 
        // Upload failed 
        Log.w(TAG, "uploadFromUri:onFailure", exception); 

        mDownloadUrl = null; 

        // [START_EXCLUDE] 
        hideProgressDialog(); 
        Toast.makeText(MainActivity.this, "Error: upload failed", 
          Toast.LENGTH_SHORT).show(); 
        updateUI(mAuth.getCurrentUser()); 
        // [END_EXCLUDE] 
       } 
      }); 
} 
// [END upload_from_uri]