【问题标题】:Issues uploading photos with Firebase使用 Firebase 上传照片的问题
【发布时间】:2017-04-05 21:23:16
【问题描述】:

我在通过 Firebase 上传图片时遇到问题。 代码如下:

//...
    //Storage
    mFirebaseStorage = FirebaseStorage.getInstance();
    mUserphotos = mFirebaseStorage.getReference().child("user/@userID");
    mTestphotos = mFirebaseStorage.getReference().child("user/testPhotos");
//...
    public void uploadImage(Uri uri) {
        Uri file = Uri.fromFile(new File("user/testPicture"));
        StorageReference testPath = mTestphotos.child("images/"+file.getLastPathSegment());
        UploadTask uploadTask = testPath.putFile(file);
        // Register observers to listen for when the download is done or if it fails
        uploadTask.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
                // Handle unsuccessful uploads
                Toast.makeText(MainActivity.this, "failure",     Toast.LENGTH_SHORT).show();
            }
        }).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();
                Toast.makeText(MainActivity.this, "It worked", Toast.LENGTH_SHORT).show();
            }
        });
//...

为了节省时间,是的,我确信 uri 得到了正确的照片。 uploadImage 还有更多内容

【问题讨论】:

  • 在此处添加您的 logcat
  • 将您的失败 Toast 更改为显示 exception.getMessage() 而不是 failure,然后告诉我们您得到了什么。

标签: android firebase firebase-storage


【解决方案1】:
    //getting the storage reference
    // filePath  is Uri
    // "uploads/" is STORAGE_PATH_UPLOADS
    StorageReference sRef = storageReference.child("uploads/" + System.currentTimeMillis() + "." + getFileExtension(filePath));

    //adding the file to reference 
    sRef.putFile(filePath)
            .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                    //displaying success toast 
                    Toast.makeText(getApplicationContext(), "File Uploaded ", Toast.LENGTH_LONG).show();

                    //creating the upload object to store uploaded image details 
                    Upload upload = new Upload(editTextName.getText().toString().trim(), taskSnapshot.getDownloadUrl().toString());

                    //adding an upload to firebase database 
                    String uploadId = mDatabase.push().getKey();
                    mDatabase.child(uploadId).setValue(upload);
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                    progressDialog.dismiss();
                    Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
                }
            })
            .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                    //displaying the upload progress 
                    double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
                    progressDialog.setMessage("Uploaded " + ((int) progress) + "%...");
                }
            });

【讨论】:

    【解决方案2】:

    试试这个,

     Uri uri = data.getData() ;// your image uri 
      StorageReference imagePathReference =   StorageRef.child("Your path");
                        Bitmap bmp = null;
                        try {
                            bmp = MediaStore.Images.Media.getBitmap(getContentResolver(), data.getData());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
    
                        // convert bitmap to byte array to save image in firebase storage
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        if (bmp != null) {
                            bmp.compress(Bitmap.CompressFormat.JPEG, 60, bos);
                        }
                        byte[] dataNew = bos.toByteArray();
    
                        uploadTask = imagePathReference.putBytes(dataNew);
                        uploadTask.addOnFailureListener(new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception exception) {
                                Log.e("firebase ", " addOnFailureListener ");
                            }
                        }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                            @Override
                            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                               // u will  et download url here.
                            }
                        });
    

    【讨论】:

      【解决方案3】:
           private void uploadimage() {
          progressbar.setMessage("Uploading Data");
          progressbar.setCanceledOnTouchOutside(false);
          progressbar.show();
          String dateStamp = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss:SSS").format(new Date()).toString();
          final StorageReference imagepath = storageReference.child("Image" + dateStamp);
          imagepath.putFile(selectedImage).addOnSuccessListener(
                  new OnSuccessListener<UploadTask.TaskSnapshot>() {
                      @Override
                      public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                          //Toast.makeText(Dashboard.this, "Image Stored Succesfully", Toast.LENGTH_LONG).show();
      
                          getimage = taskSnapshot.getDownloadUrl();
                          //  bmp = ((BitmapDrawable) imagepreview.getDrawable()).getBitmap();
                          Map<String,String> imagemap=new <String,String>HashMap();
      
                          imagemap.put("imageurl",getimage);
      
              databaseReference.child(Table_Dashboard).push().setValue(imagemap).addOnCompleteListener(new OnCompleteListener<Void>() {
                              @Override
                              public void onComplete(@NonNull Task<Void> task) {
                                  if (task.isSuccessful()) {
                                      imagepreview.setImageResource(R.mipmap.preview);
                                      progressbar.dismiss();
                                      Toast.makeText(Dashboard.this, "Image Uploaded Succesfully", Toast.LENGTH_LONG).show();
                                  }
      
                              }
                          });
                      }
                  });
      }
      

      使用上面的代码。它对我有用,希望它能解决您的错误

      【讨论】:

        猜你喜欢
        • 2021-10-18
        • 2020-06-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-02
        • 1970-01-01
        • 2011-09-30
        • 1970-01-01
        相关资源
        最近更新 更多