其他分享
首页 > 其他分享> > Android-将视频/音频文件上传到Firebase存储

Android-将视频/音频文件上传到Firebase存储

作者:互联网

我正在使用Firebase Storage保存视频/音频用户的文件.
我的主要想法是将每个视频/音频保存在用户ID(UID)下.
对每个用户而言,这意味着在其UID下保存了多个视频/音频文件.
我编写了一个代码,问题是他一直将新视频保存在我保存的旧视频上.
请告诉我我错了

   @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == PICK_VIDEO_REQUEST) {
            Uri selectedVideoUri = data.getData();
            String userUid = FirebaseAuth.getInstance().getCurrentUser().getUid();
            StorageReference storageRef = FirebaseStorage.getInstance().getReference();
            videoRef = storageRef.child("/videos/" + userUid );
            //TODO: save the video in the db
            uploadData(selectedVideoUri);
        }else if(requestCode == PICK_AUDIO_REQUEST){
            //TODO: save the audio in the db
        }
    }
}

private void uploadData(Uri videoUri) {
    if(videoUri != null){
        UploadTask uploadTask = videoRef.putFile(videoUri);

        uploadTask.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                if(task.isSuccessful())
                    Toast.makeText(getContext(), "Upload Complete", Toast.LENGTH_SHORT).show();
                    progressBarUpload.setVisibility(View.INVISIBLE);
            }
        }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                updateProgress(taskSnapshot);
            }
        });
    }else {
        Toast.makeText(getContext(), "Nothing to upload", Toast.LENGTH_SHORT).show();
    }

}

解决方法:

您每次为该用户的上传使用相同的文件路径:

videoRef = storageRef.child("/videos/" + userUid);

相反,您需要为每次上载提供一些唯一的文件名,并将用户ID视为目录组件,而不是文件本身的名称:

String filename = "you put a unique file name here";
videoRef = storageRef.child("/videos/" + userUid + "/" + filename);

标签:firebase,firebase-storage,android
来源: https://codeday.me/bug/20191025/1929304.html