2017-10-10 54 views
0

我正在捕獲圖像並將其上傳到firebase存儲。我還想將該文件的路徑保存到Firebase數據庫,以便通過使用數據庫中的該路徑將該映像用於其他位置。 我使用上傳圖片的代碼是`如何在android中的firebase數據庫中保存文件的路徑?

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

     if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK){ 

      mprogress.setMessage("Uploading image.."); 
      mprogress.show(); 
      Uri uri =data.getData(); 
      final StorageReference filePath = mStorage.child("Photos").child(uri.getLastPathSegment()); 
      filePath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { 
       @Override 
       public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { 
        mprogress.dismiss(); 
        Toast.makeText(MainActivity.this,"Upload is done...",Toast.LENGTH_SHORT).show(); 
       } 
      }); 
     } 
    } 

`

回答

1

您可以從UploadTask.TakeSnapshot變量獲取文件路徑這樣並上傳到數據庫:

private DatabaseReference mDatabase; 
// ... 
mDatabase = FirebaseDatabase.getInstance().getReference(); 

    filePath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { 
        @Override 
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { 
         mprogress.dismiss(); 
        // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL. 
         Uri downloadUrl = taskSnapshot.getDownloadUrl(); 
        //This is a sample database structure you need to create your own 
         mDatabase.child("users").child("profileImage").setValue(downloadUrl.toString()); 
        } 
       }); 
1

你可以得到filePath使用taskSnapshot.getDownloadUrl();這是返回Uri你可以通過調用獲得完整路徑Uri.toString();

致電uploadFileAndSaveToFireBase(uri)您的方法onActivityResult

private void uploadFileAndSaveToFireBase(Uri pathUri) { 
    mprogress.setMessage("Uploading image.."); 
    mprogress.show(); 
    // Get a reference to store file at chat_photos/<FILENAME> 
    StorageReference photoRef = chatPhotosStorageReference.child(pathUri.getLastPathSegment()); 
    // Upload file to FireBase Storage 
    photoRef.putFile(pathUri).addOnSuccessListener(getActivity(), new OnSuccessListener<UploadTask.TaskSnapshot>() { 

     public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { 
      mprogress.dismiss(); 
      Toast.makeText(MainActivity.this,"Upload is done...",Toast.LENGTH_SHORT).show(); 
      // When the image has successfully uploaded, we get its download URL 
      Uri downloadUrl = taskSnapshot.getDownloadUrl(); 
      // Set the download URL to the message box, so that the user can send it to the database 
      String strFilePath=downloadUrl.toString(); 
     } 
    }).addOnFailureListener(new OnFailureListener() { 

     @Override 
     public void onFailure(@NonNull Exception e) { 
      // Uh-oh, an error occurred! 
      Log.d(TAG, "onFailure: did not upload file"); 
      mprogress.dismiss(); 
     } 
    }); 
} 
相關問題