【问题标题】:how to upload to firebase a file with firebase storage如何将具有firebase存储的文件上传到firebase
【发布时间】:2016-11-05 04:47:59
【问题描述】:

我尝试将图片上传到 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);


                    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();
                            }
                        }
                    });
            }
        }

这里我将图片从数据上传到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();

        }
    }
}

请帮忙,我觉得一切都很好。

【问题讨论】:

    标签: android bitmap firebase inputstream firebase-storage


    【解决方案1】:

    ** 这不会以全分辨率保存图像 ** 要以全分辨率保存图片,请在启动 TakePictureIntent 时研究如何执行此操作。

    我遇到了同样的错误,并通过像这样设置我的拍照和上传来解决它:

        //takes the picture
        private void dispatchTakePictureIntent() {
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
                startActivityForResult(takePictureIntent, 1);
            }
        }
    
        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
                //saves the pic locally
                Bundle extras = data.getExtras();
                Bitmap imageBitmap = (Bitmap) extras.get("data");
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                byte[] dataBAOS = baos.toByteArray();
    
                /***************** UPLOADS THE PIC TO FIREBASE*****************/
                // Points to the root reference
                StorageReference storageRef = FirebaseStorage.getInstance().getReferenceFromUrl("your-root-storage-ref");
                StorageReference imagesRef = storageRef.child("image");
    
                UploadTask uploadTask = imagesRef.putBytes(dataBAOS);
                uploadTask.addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception exception) {
                        // Handle unsuccessful uploads
                    }
                }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
                        Uri downloadUrl = taskSnapshot.getDownloadUrl();
                    }
                });
            }
        }
    

    这样,它将使用此文件结构压缩您的图像并将其保存在您的 Firebase 存储中:

    根 -> 图像

    【讨论】:

      【解决方案2】:

      您可以将InputStream 直接从Uri 传递给putStream 方法。您可能想在上传之前自己调整图像大小,这需要更多的工作,但这种方式在客户端使用的内存非常少。

          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);
          }
      

      【讨论】:

        猜你喜欢
        • 2020-04-08
        • 2018-06-21
        • 2019-02-10
        • 1970-01-01
        • 2020-05-07
        • 2019-11-06
        • 1970-01-01
        • 1970-01-01
        • 2020-09-08
        相关资源
        最近更新 更多