如何在将文件上传到Firebase后获取文件URL?

时间:2017-04-26 18:30:10

标签: android firebase firebase-storage

将文件上传到Firebase后,您如何获取该网址,以便将其存储以供日后使用?我想将URL写入Firebase数据库,以便其他用户可以访问该图像。

我正在上传文件:

public void uploadFile()
{

    StorageReference filepath = mstorageRef.child("folder").child(filename);

    Uri File= Uri.fromFile(new File(mFileName));

    filepath.putFile(File).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
        {
            Toast.makeText(MtActivity.this, "Upload Done", Toast.LENGTH_LONG).show();
        }
    });
}

我已确认文件实际上已上传,所以现在我只需要可以写入数据库的URL。但是,当我尝试这样做时:

Uri downloadUrl = taskSnapshot.getMetadata().getDownloadUrl();

它给了我一个错误并说This method should only be accessed from tests or within private scope

我不确定这意味着什么,而且我也不知道为什么我会收到错误,因为我关注了Firebase提供的this example

是否有获取网址的新方式?

此外,特定于该项目的URL是否是唯一的?这意味着如果我将它存储到数据库并稍后尝试访问它,我能够这样做吗?

13 个答案:

答案 0 :(得分:23)

您正在使用已弃用的private IAuthenticationManager Authentication => this.Request.GetOwinContext().Authentication; 。您可以使用StorageReference.getDownloadUrl()

在您的情况下,您可以尝试this作为 -

UploadTask.getDownloadUrl()

注意 filepath.putFile(File).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { filepath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() { @Override public void onSuccess(Uri uri) { Uri downloadUrl = uri; //Do what you want with the url } Toast.makeText(MtActivity.this, "Upload Done", Toast.LENGTH_LONG).show(); } }); 返回任务,必须异步处理,你不能StorageReference.getDownloadUrl()否则你将获得Uri downloadUrl = photoRef.getDownloadUrl().getResult();

答案 1 :(得分:3)

这种方法也有效,而且更简单。

它不是&#34;令人难以置信的&#34;,但它会将您的代码减少到几行。希望这是一个有用的答案。

StorageReference filepath = mstorageRef.child("folder").child(filename);
filepath.putFile(File).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot){
            Uri downloadUrl = filepath.getDownloadUrl();  // here is Url for photo  
            Toast.makeText(MtActivity.this, "Upload Done", Toast.LENGTH_LONG).show();
        }
});

答案 2 :(得分:1)

我在这里很热

1)这是我的上载并获取http网址代码:

UploadTask uploadTask = FirebaseStorage.getInstance().getReference().child("id").child("filename")
                                .putFile(uri);
                        Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
                            @Override
                            public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                                if (!task.isSuccessful()) {
                                    throw task.getException();
                                }

                                // Continue with the task to get the download URL
                                return FirebaseStorage.getInstance().getReference().child(user.getUid()).child(avatarName).getDownloadUrl();
                            }
                        }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                            @Override
                            public void onComplete(@NonNull Task<Uri> task) {
                                if (task.isSuccessful()) {
                                    Uri downloadUri = task.getResult();
                                    FirebaseDatabase.getInstance().getReference().child(user.getUid())
                                            .child(avatarName)
                                            .child("avatar_image")
                                            .setValue(downloadUri.toString());
                                    Toast.makeText(getContext(), "Success", Toast.LENGTH_SHORT).show();
                                } else {
                                    // Handle failures
                                    // ...
                                    Toast.makeText(getContext(), "Failed", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });

2)这是我从图库中拾取图像后的onActivityResult代码

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

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

        uri = data.getData();

        try {
            bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), uri);
            // Log.d(TAG, String.valueOf(bitmap));
            ivAvatarPic.setImageBitmap(bitmap);
            //ImageView imageView = (ImageView) findViewById(R.id.imageView);
            //imageView.setImageBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

答案 3 :(得分:1)

如上所述,StorageReference.getDownloadUrl() 返回Task。

这是我的代码:

        filepath.putFile(imageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                if(task.isSuccessful()){

                    filepath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                        @Override
                        public void onSuccess(Uri uri) {
                            Uri downloadUri = uri;
                            String download_url = uri.toString();
                            mUserDatabase.child("image").setValue(download_url).addOnCompleteListener(new OnCompleteListener<Void>() {
                              @Override

                                public void onComplete(@NonNull Task<Void> task) {

                                   if(task.isSuccessful()) {

                                          mProgressDialog.dismiss();
                                          Toast.makeText(SettingActivity.this, "Successfully uploaded", Toast.LENGTH_LONG).show();

                                   }else {
                                       Toast.makeText(SettingActivity.this, "Error happened during the upload process", Toast.LENGTH_LONG).show();
                                   }
                                }
                            });
                        }
                    });


                }else{
                    Toast.makeText(SettingActivity.this, "Error happened during the upload process", Toast.LENGTH_LONG ).show();
                }
            }
        });

答案 4 :(得分:1)

尝试这个:

 filepath.putFile(File).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
         @Override
         public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
            if(task.isSuccessful()){
                 String fileUri = task.getResult().getUploadSessionUri().toString();
                         // Do whatever you want with fileUri 

                        }
                   }
            }) ;

答案 5 :(得分:0)

使用以下代码

val imageGalleryRef = storageReference?.child(name + "_gallery")
            val uploadTask = imageGalleryRef.putFile(file)
            uploadTask.addOnFailureListener({ e ->
                Log.e(TAG, "onFailure sendFileFirebase " + e.message)
            }).addOnCompleteListener(
                    object : OnCompleteListener<UploadTask.TaskSnapshot> {
                        override fun onComplete(p0: Task<UploadTask.TaskSnapshot>) {
                            imageGalleryRef.downloadUrl.addOnSuccessListener { e ->
                                run {
                                     downloadUrl = e.toString() // e is image download Uri
                                }
                            }
                        }
                    }

            )

答案 6 :(得分:0)

 filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                            @Override
                            public void onSuccess(Uri uri) {
                                String category = spinner.getSelectedItem().toString();
                                String title = ((EditText) findViewById(R.id.post_title)).getText().toString();
                                String description = ((EditText) findViewById(R.id.post_description)).getText().toString();
                                final Post post = new Post(userId, category, title, description, latitude, longitude, true);
                                post.setAddressList(addressLine);
                                post.setContact(contact);

                                if (addressLine != null) {
                                    post.setPlace(addressLine.split(",")[2]);
                                }
                                post.setId(key);
                                post.setImage(uri.toString());
                                databaseReference.setValue(post).addOnCompleteListener(new OnCompleteListener<Void>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {
                                        if (task.isSuccessful()) {

                                            ((EditText) findViewById(R.id.post_title)).setText("");
                                            ((EditText) findViewById(R.id.post_description)).setText("");
                                            postImageButton.setImageURI(null);
                                            progressBarDialog.dismiss();
                                            Toast.makeText(PostActivity.this, "Your request is sucessfully completed", Toast.LENGTH_SHORT).show();
                                        } else if (!task.isSuccessful()) {
                                            progressBarDialog.dismiss();
                                            Toast.makeText(PostActivity.this, "Your request is not completed", Toast.LENGTH_SHORT).show();
                                        }

                                    }
                                });
                            }

                        });
                    }

答案 7 :(得分:0)

URI 更改为 URL

val urlTask = uploadTask.continueWith { task ->
            if (!task.isSuccessful) {
                task.exception?.let {
                    throw it
                }
            }


            spcaeRef.downloadUrl
        }.addOnCompleteListener { task ->
            if (task.isSuccessful) {

                val downloadUri = task.result

                //URL
                val url = downloadUri!!.result

            } else {
                //handle failure here
            }
        }

答案 8 :(得分:0)

在Ionic 5 +电容器中,这就是我最终能够监视上传并获取完成的文件名的方式。

该代码是从Google自己的文档以及一些Google搜索(https://ionicthemes.com/tutorials/about/ionic-firebase-image-upload等)中收集的。

据我所知,它正在使用画布从图像生成base64字符串。那行得通,而ionic的File和Base64却没有。

在页面上,我有一个显示百分比(this.downloadProgress)(如果> 0)。我还有一个,其中src = this.imageUrl在显示该图片时已上传。

我无法获得上述答案中的任何技术来工作,甚至无法编译。但是我还是不知道为什么。

另一个警告是某些示例代码使用function()而不是箭头语法

encodeImageUri(imageURI,function(image64){

需要重写为箭头语法,才能将“ this”绑定/传递给所调用的函数,例如:

encodeImageUri(imageURI,image64 => {

    uploadImage(imageURI) {
    console.log(`try upload ${imageURI}`)
      let storageRef = firebase.storage().ref();
      let imageRef = storageRef.child('image').child('imageName');
      this.encodeImageUri(imageURI, image64 => {

        // create upload task
        const uplTask = imageRef.putString(image64, 'data_url');

        uplTask.on('state_changed',
          snapshot => {
            var progress = (snapshot.bytesTransferred / snapshot.totalBytes);
            console.log('Upload is ' + progress * 100 + '% done'); // might display this somewhere
            this.downloadProgress = progress; // update progress bar
          },
          error => {
            console.log('upload error');
          },
          () => {
            uplTask.snapshot.ref.getDownloadURL()
              .then(downloadURL => {
                console.log('File available at', downloadURL);
                this.imageUrl = downloadURL;
                this.downloadProgress = -1; // negative values hide the progress bar
              });        
          }
        );
      });
  }

  encodeImageUri(imageUri, callback) {
    var c = document.createElement('canvas');
    var ctx = c.getContext("2d");
    var img = new Image();
    img.onload = function () {
      var aux:any = this;
      c.width = aux.width;
      c.height = aux.height;
      ctx.drawImage(img, 0, 0);
      var dataURL = c.toDataURL("image/jpeg");
      callback(dataURL);
    };
    img.src = imageUri;
  };

这当然很无聊,因为它总是会覆盖相同的Firebase存储文件:)但这是可以解决的。

答案 9 :(得分:0)

不确定这是您在使用Kotlin时要寻找的东西。这就是我当前项目中的工作方式。我希望它将对以后的其他人有所帮助。

首先,我要从相机或图库中获取图像。 我正在使用当前时间戳来使文件名唯一。

fun uploadFileFromMemory() {

        showLoading()

        val currentTimestamp = System.currentTimeMillis()

        val storage = Firebase.storage("Your storage url")

        // Create a storage reference from our app
        val storageRef = storage.reference

        // Create a reference to "mountains.jpg"
        val mountainsRef = storageRef.child("images/picture$currentTimestamp.jpg")

        // Get the data from an adminImageView as bytes
        adminImageView.isDrawingCacheEnabled = true
        adminImageView.buildDrawingCache()
        val bitmap = (adminImageView.drawable as BitmapDrawable).bitmap
        val baos = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos)
        val data = baos.toByteArray()

        var uploadTask = mountainsRef.putBytes(data)

        val urlTask = uploadTask.continueWithTask { task ->
            if (!task.isSuccessful) {
                task.exception?.let {
                    throw it
                }
            }
            mountainsRef.downloadUrl
        }.addOnCompleteListener { task ->
            if (task.isSuccessful) {
                val downloadUri = task.result

                updateServicePicture(downloadUri.toString())

            } else {
                hideLoading()

                showToast("Something went wrong")
            }
        }

之后,我将使用此功能获取新更新文件的URL,以更新我的Firestore数据库中的图片URL属性。

fun updateServicePicture(url: String) {

        val db = FirebaseFirestore.getInstance()

        val id = arguments?.getString("id")

        if (id !== null) {

            val ref = db.collection("services").document(id)

// Set the "isCapital" field of the city 'DC'
            ref
                .update("picture", url)
                .addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully updated!")

                    hideLoading()

                    showToast("Picture has been successfully updated")
                }
                .addOnFailureListener { e -> Log.w(TAG, "Error updating document", e)

                    hideLoading()

                    showToast("Something went wrong")
                }

        }
    }

hideLoading(),showloading()和showToast()是我的Progressbar和Toast的函数。 我希望这可以帮助某人。 通过文档和一些测试,我最终使它开始工作。祝大家编码愉快。

答案 10 :(得分:0)

  Future<List<String>> uploadImages(List<String> filepaths) async {
    List<String> uploadUrls = [];

    await Future.wait(filepaths.map((String filepath) async {
      FirebaseStorage storage = FirebaseStorage(storageBucket: 'gs://your-bucket-name.appspot.com');
      StorageUploadTask uploadTask = storage.ref().child("images/${basename(filepath)}").putFile(File(filepath));
      StorageTaskSnapshot storageTaskSnapshot;

      StorageTaskSnapshot snapshot = await uploadTask.onComplete;
      if (snapshot.error == null) {
        storageTaskSnapshot = snapshot;
        final String downloadUrl = await storageTaskSnapshot.ref.getDownloadURL();
        uploadUrls.add(downloadUrl);

        print('Upload success');
      } else {
        print('Error from image repo ${snapshot.error.toString()}');
        throw ('This file is not an image');
      }
    }), eagerError: true, cleanUp: (_) {
      print('eager cleaned up');
    });

    return uploadUrls;
  }
}

答案 11 :(得分:-1)

你试过taskSnapshot.getDownloadUrl()吗? 如果这也不起作用,您可以通过mstorageRef.child("folder").child(filename).toString()

获取成功监听器中的图像位置

答案 12 :(得分:-1)

试试这个:

final Uri uri = data.getData();

StorageReference filepath = mStorageRef.child("folder").child(filename);
filepath.putFile(uri).addOnSuccessListener(new 

OnSuccessListener<UploadTask.TaskSnapshot>() {

        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

            Uri downloadUri = taskSnapshot.getDownloadUrl();
            //Getting url where image is stored
            //downloadUri will store image URI
        }
    });