如何使用Firebase存储将文件上传到Firebase [英] how to upload to firebase a file with firebase storage

查看:839
本文介绍了如何使用Firebase存储将文件上传到Firebase的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图上传到firebase的图片,当我上传它显示我的文件的大小是0字节,不显示内容图片



一切似乎好吧,那么它会发生什么???

  StorageReference storageRef = storage.getReferenceFromUrl(gs://< your-bucket -name>中); 

if(inputStream!= null){

String pic =BathroomImage+ + rand.nextInt(1000)+.jpg;
mountainsRef = storageRef.child(pic);
uploadTask = mountainsRef.putStream(inputStream);

$ b uploadTask.addOnFailureListener(new OnFailureListener(){
@Override
public void onFailure(@NonNull Exception e){
Log.d(这是无聊:,嘿我在这里);
}
})。addOnSuccessListener(new OnSuccessListener< UploadTask.TaskSnapshot>(){
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot){
taskSnapshot.getMetadata();
Uri downloadUri = taskSnapshot.getDownloadUrl();
bitmap.recycle();
bitmap = null;
System.gc();

try {
inputStream.close();
} catch(IOException e){
e.printStackTrace();
}
}
});






$ p这里我把图片从数据上传到inputsream。

  void TakePickphoto(){
Intent galleryIntent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images .Media.EXTERNAL_CONTENT_URI); //创建意图打开图像应用程序,如图库,谷歌照片
startActivityForResult(galleryIntent,RESULT_LOAD_IMAGE); //启动意图
$ b $公共无效onActivityResult(最终诠释requestCode,最终诠释resultCode,最后意图数据){
super.onActivityResult(requestCode,resultCode,data);

$ b $ if(requestCode == RESULT_LOAD_IMAGE&& resultCode == getActivity()。 ); //从数据获取URI映像

handler = new Handler();
尝试{
Thread.sleep(50);
} catch(InterruptedException e){
e.printStackTrace();
}
Runnable runnable = new Runnable(){
@Override
public void run(){
try {

inputStream = context 。.getContentResolver()openInputStream(data.getData());
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
bitmap = BitmapFactory.decodeStream(inputStream,new Rect(40,40,40,40),options);
$ b $ catch(FileNotFoundException e){
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();

$ b $ handler.post(new Runnable(){
@Override
public void run(){
ImageView imageView;
imageView =(ImageView)view.findViewById(R.id.imageView2);
imageView.setImageBitmap(bitmap);

$ b}
});
}
};
new Thread(runnable).start();



$ b $ / code $ / pre
$ b $ p请帮忙,一切看起来都很好。

解决方案

您可以将 InputStream 直接从 Uri putStream 方法。您可能希望在上传图片之前自行调整图片大小,这需要更多的工作,但这种方式在客户端使用的内存很少。

 if(requestCode == IMAGE_PICKER_SELECT&& resultCode == Activity.RESULT_OK){
Uri imageUri = data.getData();
尝试{
ContentResolver contentResolver = getActivity()。getContentResolver();
StorageMetadata storageMetadata = new StorageMetadata.Builder()
.setContentType(contentResolver.getType(imageUri))
.build();
FirebaseStorage.getInstance()。getReference()
.child(users)
.child(FirebaseAuth.getInstance()。getCurrentUser()。getUid())
。 child(UUID.randomUUID()。toString())
.putStream(contentResolver.openInputStream(imageUri),storageMetadata)
.addOnSuccessListener(getActivity(),new OnSuccessListener< UploadTask.TaskSnapshot>(){
@Override
public void onSuccess(UploadTask.TaskSnapshot task){
Uri downloadUrl = task.getDownloadUrl();
Toast.makeText(getActivity(),R.string.image_successfully_uploaded, Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(getActivity(),new OnFailureListener(){
@Ov erride
public void onFailure(@NonNull Exception e){
Toast.makeText(getActivity(),R.string.error_uploading_image,Toast.LENGTH_LONG).show();
}
});
} catch(IOException e){

}

} else {
super.onActivityResult(requestCode,resultCode,data);
}


i try to upload to firebase a picture and when i upload its show me that the size of the file is 0 bytes and dont show the content picture

everything seems fine, then whay its happen???

  StorageReference storageRef = storage.getReferenceFromUrl("gs://<your-bucket-name>");

                if (inputStream!=null) {

                    String pic = "BathroomImage" + +rand.nextInt(1000) + ".jpg";
                    mountainsRef = storageRef.child(pic);
                    uploadTask = mountainsRef.putStream(inputStream);


                    uploadTask.addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Log.d("this is the faiure:","hey im here");
                        }
                    }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            taskSnapshot.getMetadata();
                            Uri downloadUri = taskSnapshot.getDownloadUrl();
                            bitmap.recycle();
                            bitmap=null;
                            System.gc();

                            try {
                                inputStream.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });
            }
        }

here i upload the picture from the data to inputsream.

  void TakePickphoto(){
        Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); // Create intent to Open Image applications like Gallery, Google Photos
        startActivityForResult( galleryIntent, RESULT_LOAD_IMAGE);// Start the Intent

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


        if (requestCode == RESULT_LOAD_IMAGE && resultCode ==getActivity().RESULT_OK && null != data) {
            selectedImage = data.getData(); // Get the  URI Image from data

            handler= new Handler();
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    try {

                        inputStream = context.getContentResolver().openInputStream(data.getData());
                        BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inSampleSize =4;
                        bitmap = BitmapFactory.decodeStream(inputStream, new Rect(40,40,40,40),options);

                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            ImageView imageView;
                            imageView = (ImageView) view.findViewById(R.id.imageView2);
                            imageView.setImageBitmap(bitmap);


                        }
                    });
                }
            };
            new Thread(runnable).start();

        }
    }
}

please help, everything look fine to me.

解决方案

You can pass the InputStream directly from the Uri to the putStream method. You may want to resize the image yourself before uploading it, which would require a bit more work, but this way uses very little memory on the client side.

    if (requestCode == IMAGE_PICKER_SELECT && resultCode == Activity.RESULT_OK) {
        Uri imageUri = data.getData();
        try {
            ContentResolver contentResolver = getActivity().getContentResolver();
            StorageMetadata storageMetadata = new StorageMetadata.Builder()
                    .setContentType(contentResolver.getType(imageUri))
                    .build();
            FirebaseStorage.getInstance().getReference()
                    .child("users")
                    .child(FirebaseAuth.getInstance().getCurrentUser().getUid())
                    .child(UUID.randomUUID().toString())
                    .putStream(contentResolver.openInputStream(imageUri), storageMetadata)
                    .addOnSuccessListener(getActivity(), new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot task) {
                            Uri downloadUrl = task.getDownloadUrl();                               
                            Toast.makeText(getActivity(), R.string.image_successfully_uploaded, Toast.LENGTH_LONG).show();
                        }
                    })
                    .addOnFailureListener(getActivity(), new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast.makeText(getActivity(), R.string.error_uploading_image, Toast.LENGTH_LONG).show();
                        }
                    });
        } catch (IOException e) {

        }

    } else {
        super.onActivityResult(requestCode, resultCode, data);
    }

这篇关于如何使用Firebase存储将文件上传到Firebase的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆