将“多个”文件上传和下载到Firebase Cloud Storage

时间:2019-09-18 12:07:53

标签: java android firebase firebase-storage

我有一个可以上载到Firebase存储中的工作代码,但是当我上传文件时,文件会相互覆盖。 Firebase似乎也无法上传具有原始名称的文件,因此我必须使用fileUri.getPath().get(1)为文件指定一个自定义名称,但是似乎给它们起了相同的名称

我曾尝试使用Firebase UId来区分它们,但是尝试使用另一个用户帐户将文件下载回时会出现问题,因为uid会有所不同。

 private void executeUploadTask() {
        showProgressBar();
        //FilePaths filePaths = new FilePaths();
        //specify where the photo will be stored
        final StorageReference storageReference = FirebaseStorage.getInstance().getReference()
                .child("classroom/" + mSelectedFileUri.getPathSegments().get(0) + ".jpg"); //just replace the old image with the new one

        // Create file metadata including the content type
        StorageMetadata metadata = new StorageMetadata.Builder()
                .setContentType("classroom/files")
                .setContentLanguage("en") //see nodes below
                .build();
        //if the file size is valid then we can submit to database
        UploadTask uploadTask = null;
        uploadTask = storageReference.putFile(mSelectedFileUri, metadata);
        //uploadTask = storageReference.putBytes(mBytes); //without metadata

        uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                //Now insert the download url into the firebase database

                //Task<Uri> firebaseURL = taskSnapshot.getStorage().getDownloadUrl();
                Toast.makeText(ClassroomActivity.this, "Upload Success", Toast.LENGTH_SHORT).show();
                okay = true;
                //mSelectedFileUri = null;
                //Log.d("newTag", "onSuccess: firebase download url = " + firebaseURL.toString());
//                FirebaseDatabase.getInstance().getReference()
//                        .child(getString(R.string.dbnode_users))
//                        .child(FirebaseAuth.getInstance().getCurrentUser().getUid())
//                        .child(getString(R.string.field_profile_image))
//                        .setValue(firebaseURL.toString());
                hideProgressBar();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
                Toast.makeText(ClassroomActivity.this, "could not upload file", Toast.LENGTH_SHORT).show();
                hideProgressBar();
            }
        }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                double currentProgress = (100 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
                if (currentProgress > (progress + 15)) {
                    progress = (100 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
                    Log.d(TAG, "onProgress: Upload is " + progress + "% done");
                    Toast.makeText(ClassroomActivity.this, progress + "%", Toast.LENGTH_SHORT).show();
                }
            }
        });

        //********************************************************//
        //creating the file's reference to the database
        User user = new User();
        final FileDetails fileDetails = new FileDetails();
        DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
        //fileDetails.setDownloadURL(downloadFile());

        //*******//
        final DatabaseReference ref2 = FirebaseDatabase.getInstance().getReference();
        Query query = ref2.child(getString(R.string.dbnode_users))
                .orderByKey()
                .equalTo(FirebaseAuth.getInstance().getCurrentUser().getUid());
        query.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                //this loop will return a single result
                for (DataSnapshot singleSnapshot : dataSnapshot.getChildren()) {
                    Log.d("TAG", "onDataChange: (QUERY METHOD 1) found user: "
                            + singleSnapshot.getValue(User.class).toString());
                    FileDetails fileDetails1 = singleSnapshot.getValue(FileDetails.class);
                    fileDetails.setName(fileDetails1.getName());
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        });
        //*******//
        fileDetails.setFileName(mSelectedFileUri.getLastPathSegment());
        fileDetails.setThumbnailURL("");
        reference.child(getString(R.string.dbnode_uploads))
                .child("files")
                .setValue(fileDetails).addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
            }
        });
        mSelectedFileUri = null;
        downloadURL = null;

        Log.d("newTag", "details: " + fileDetails.toString() + " -> " + fileDetails.getName());
        //********************************************************//
    }

0 个答案:

没有答案