如何将音频文件上传到Firebase存储?

时间:2019-11-10 14:26:56

标签: android firebase-storage

我想将保存在移动内存中的音频文件上传到Firebase存储器。这是我的代码

TextView filePathText;
Button sUrlBtn, upload;
Uri audio_uri = null;

public class AddPostActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_post);

        filePathText = findViewById(R.id.filePathText);
        upload = findViewById(R.id.add_upload);
        sUrlBtn = findViewById(R.id.add_filePath);

        sUrlBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("*/*");
                startActivityForResult(intent, 10);
            }
        });
        ...
        upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String fileName = filePathText.getText().toString().trim();
                fileName += "/test.mp3";

                Uri uri = Uri.fromFile(new File(fileName));
                uploadData(fileName, uri);
            }
        }
    });

private void uploadData(final String file, final Uri uri) {
    ...
    StorageReference ref = FirebaseStorage.getInstance().getReference();
    ref.child("tAudio").child("test_audio.mp3").putFile(uri)
        .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
                while (!uriTask.isSuccessful()) ;

                if (uriTask.isSuccessful()) {
                    audio_uri = null;
                }
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.d("AddPostActivity", "TEST onFailure()...\nException : " + e.getMessage());
            }
        });
}
...

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == 10) {
            audio_uri = data.getData();
            filePathText.setText(audio_uri.getEncodedPath());
        } 
    }
    super.onActivityResult(requestCode, resultCode, data);
}

我想做的是... 1.单击sUrlBtn,从内部音频文件中获取文件路径。 2.单击upload

,将该音频文件上传到Firebase存储

但是当我上传该文件时,e.getMessage()就是这样。 异常:发生未知错误,请检查HTTP结果代码和服务器响应的内部异常。 有什么解决方案可以将文件从android移动内存上传到Firebase存储吗?

0 个答案:

没有答案