简体   繁体   中英

Pushing Firebase storage download URLs to Firebase cloud Firestore

How can I push the download URL of Firebase storage files to the Firestore cloud? I have a project that can upload PDF files to Firestore storage, but I can't push the download URL of the uploaded files to the Firestore cloud.

I need to catch the upload URL for every single file and send it to the document in the firestore to be able to download it. I'm uploading and downloading PDF files.

Here is my code:

public class pdfUploader extends AppCompatActivity {
    private StorageReference mStorageRef;
    Button upload;
    Button select;
    int CODE=215;
    private CollectionReference dbFirestore;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pdf_uploader);
        mStorageRef = FirebaseStorage.getInstance().getReference();
        upload = findViewById(R.id.upload);
        select = findViewById(R.id.choose);
        select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectFile();
            }
        });
    }

    public void selectFile () {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.setType("*/*");
        startActivityForResult(Intent.createChooser(i,"Select a file"), CODE);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        String filePath = data.getDataString();
        Uri SelectedFileLocation=Uri.parse(filePath);
        UploadFile(SelectedFileLocation);
        super.onActivityResult(requestCode, resultCode, data);
    }

    public  void UploadFile( Uri file) {
        Toast.makeText(this, "Please wait.. the file is uploading!", Toast.LENGTH_SHORT).show();
        //Uri file = Uri.fromFile(new File("path/to/images/rivers.jpg"));
        StorageReference riversRef = mStorageRef.child(Objects.requireNonNull(file.getLastPathSegment()));
        riversRef.putFile(file)
            .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    Toast.makeText(pdfUploader.this, "Upload Success", Toast.LENGTH_SHORT).show();
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                    Toast.makeText(pdfUploader.this, "Upload Failed", Toast.LENGTH_SHORT).show();

                }
            });
    }
}

Assign this Variable on Top

FirebaseFirestore db;

//In oncreateView we have to assign now db so.
db = FirebaseFirestore.getInstance();

Code for get File uri :

riversRef.putFile(File).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
    {
        riversRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                @Override
                public void onSuccess(Uri uri) {
                    Uri downloadUrl = uri;
                    Toast.makeText(MtActivity.this, "Upload Done", Toast.LENGTH_LONG).show();   
                    //After upload Complete we have to store the Data to firestore.
                    Map<String, Object> file = new HashMap<>();
                    file.put("url", downloadUrl.toString()); // We are using it as String because our data type in Firestore will be String
                    db.collection("/*Put you're collection name*/").document("/*And Document name Here*/")
                            .set(file)
                            .addOnSuccessListener(new OnSuccessListener<Void>() {
                                @Override
                                public void onSuccess(Void aVoid) {
                                    Log.d(TAG, "DocumentSnapshot successfully written!");
                                }
                            })
                            .addOnFailureListener(new OnFailureListener() {
                                @Override
                                public void onFailure(@NonNull Exception e) {
                                    Log.w(TAG, "Error writing document", e);
                                }
                            });
                }
    }
});

If download url expires there's better way to store you're image file in you're storage and firestore

Code :

riversRef.putFile(file)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        String path = //Put path of storage it will be something like [images/filename.jpg(Put your extension of file)] this path from firebase storage
                        Map<String, Object> file = new HashMap<>();
                        file.put("url", path); // We are using it as String because our data type in Firestore will be String
                        db.collection("/*Put you're collection name*/").document("/*And Document id Here*/")
                                .set(file)
                                .addOnSuccessListener(new OnSuccessListener<Void>() {
                                    @Override
                                    public void onSuccess(Void aVoid) {
                                        Log.d(TAG, "DocumentSnapshot successfully written!");
                                    }
                                })
                                .addOnFailureListener(new OnFailureListener() {
                                    @Override
                                    public void onFailure(@NonNull Exception e) {
                                        Log.w(TAG, "Error writing document", e);
                                    }
                                });
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception exception) {
                        Toast.makeText(pdfUploader.this, "Upload Failed", Toast.LENGTH_SHORT).show();

                    }
                });

the above code will be useful and better when you're dealing with images and read this docs for further details

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM