【问题标题】:FireBase Storage Image Upload AndroidFireBase 存储图像上传 Android
【发布时间】:2018-07-04 03:09:49
【问题描述】:

我创建了一个使用 Firebase 存储运行的应用。这个想法是您从照片库中选择一张图片,然后将其上传到 Firebase 存储。与 Firebase 的连接似乎工作正常,我可以选择一个图像。当我按下提交按钮将其上传到 Firebase 时,就会出现问题。

当我单击它一次时,什么也没有发生。

当我点击几次时,我收到消息“发生未知错误,请检查 HTTP 结果代码和内部异常”..

怎么办,求指教..

来自清单:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>

来自活动:

public class PostActivity extends AppCompatActivity {

private static final int GALLERY_REQUEST = 2;
private Uri uri = null;
private ImageButton imageButton;
private EditText editName;
private EditText editDescription;
private StorageReference storageReference;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_post);
    //reference the two edittext Views, initialize them
    editName = (EditText) findViewById(R.id.editName);
    editDescription = (EditText) findViewById(R.id.editDescription);

    //add the reference to the storagereference, initialize it
    storageReference = FirebaseStorage.getInstance().getReference();
}

public void ImageButtonClicked (View view){
    Intent galleryintent = new Intent (Intent.ACTION_GET_CONTENT);
    galleryintent.setType("Image/*");  
    startActivityForResult(galleryintent, GALLERY_REQUEST);
}

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

if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK){

uri = data.getData();
imageButton = (ImageButton) findViewById(R.id.imageButton);
imageButton.setImageURI(uri);
    }
}

public void submitButtonClicked (View view){

    String titleValue = editName.getText().toString().trim();
    String titleDescription = editDescription.getText().toString().trim();

    if (!TextUtils.isEmpty(titleValue) && !TextUtils.isEmpty(titleDescription)){

        StorageReference filePath = storageReference.child("PostImage").child(uri.getLastPathSegment());

        filePath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

Uri downloadurl = taskSnapshot.getDownloadUrl();
Toast.makeText(PostActivity.this,"uploadcomplete",Toast.LENGTH_LONG).show();

            }
        });
filePath.putFile(uri).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {

       Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();

【问题讨论】:

标签: android firebase firebase-storage


【解决方案1】:

尝试使用此方法将图像上传到 Firebase 存储:

private void uploadMethod() {
        progressDialog();
        FirebaseStorage firebaseStorage = FirebaseStorage.getInstance();
        StorageReference storageReferenceProfilePic = firebaseStorage.getReference();
        StorageReference imageRef = storageReferenceProfilePic.child("Your Path" + "/" + "Image Name" + ".jpg");

        imageRef.putFile(imageUri)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        //if the upload is successful
                        //hiding the progress dialog
                        //and displaying a success toast
                        dismissDialog();
                        String profilePicUrl = taskSnapshot.getDownloadUrl().toString();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception exception) {
                        //if the upload is not successful
                        //hiding the progress dialog
                        dismissDialog();
                        //and displaying error message
                        Toast.makeText(getActivity(), exception.getCause().getLocalizedMessage(), Toast.LENGTH_LONG).show();
                    }
                })
                .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                        //calculating progress percentage
//                        double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
//                        //displaying percentage in progress dialog
//                        progressDialog.setMessage("Uploaded " + ((int) progress) + "%...");
                    }
                });

    }

【讨论】:

    【解决方案2】:

    我通过 Rahul Chandrabhan 的代码找到了答案。 我更改的是删除以下方法的最后一部分:

    StorageReference filePath = 
    storageReference.child("PostImage").child(uri.getLastPathSegment());
    
    TO 
    
    StorageReference filePath = storageReference.child("PostImage");
    

    【讨论】:

      【解决方案3】:

      要在 Firebase 上执行图片上传,请使用以下方法:

      void uploadFile(String pathToFile, String fileName, String serverFolder, String contentType) {
          if (pathToFile != null && !pathToFile.isEmpty()) {
      
              File file = new File(pathToFile);
              if (file.exists()) {
      
                  Uri uri = Uri.fromFile(new File(pathToFile));
      
                  // Create a storage reference from our app
                  mStorageRef = mFirebaseStorage.getReference();
      
                  // Create a reference to "mountains.jpg"
                  //StorageReference mountainsRef = storageRef.child(fileName);
      
                  // Create a reference to 'images/mountains.jpg'
                  StorageReference mountainImagesRef = mStorageRef.child(serverFolder+"/" + fileName);
                  StorageMetadata metadata = null;
                  if (contentType != null && !contentType.isEmpty()) {
                      // Create file metadata including the content type
                      metadata = new StorageMetadata.Builder()
                              .setContentType(contentType)
                              .build();
                  }
      
      
                  if (metadata != null) {
                      uploadFileTask = mountainImagesRef.putFile(uri, metadata);
                  } else {
                      uploadFileTask = mountainImagesRef.putFile(uri);
                  }
      
                  uploadFileTask.addOnFailureListener(new OnFailureListener() {
                      @Override
                      public void onFailure(@NonNull Exception exception) {
                          // Handle unsuccessful uploads
                          hideProgressDialog();
                          exception.printStackTrace();
                          Log.e(TAG,exception.getMessage());
                          if (firebaseUploadCallback!=null)
                          {
                              firebaseUploadCallback.onFirebaseUploadFailure(exception.getMessage());
                          }
                      }
                  });
                  uploadFileTask.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.
                          hideProgressDialog();
                          Uri downloadUrl = taskSnapshot.getDownloadUrl();
                          Log.e(TAG, "Upload is success "+ downloadUrl);
                          if (firebaseUploadCallback!=null)
                          {
                              firebaseUploadCallback.onFirebaseUploadSuccess("Upload is success "+ downloadUrl.toString(), downloadUrl.toString());
                          }
                      }
                  });
                  // Observe state change events such as progress, pause, and resume
                  uploadFileTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                      @Override
                      public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                          hideProgressDialog();
                          double progressPercent = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
                          progressPercent = Double.parseDouble(FirebaseUtil.formatDecimal(progressPercent,2));
                          Log.e(TAG, "File Upload is " + progressPercent + "% done");
                          if (firebaseUploadCallback!=null)
                          {
                              firebaseUploadCallback.onFirebaseUploadProgress(progressPercent);
                          }
                      }
                  });
                  uploadFileTask.addOnPausedListener(new OnPausedListener<UploadTask.TaskSnapshot>() {
                      @Override
                      public void onPaused(UploadTask.TaskSnapshot taskSnapshot) {
                          hideProgressDialog();
                          Log.e(TAG, "Upload is paused");
                          if (firebaseUploadCallback!=null)
                          {
                              firebaseUploadCallback.onFirebaseUploadPaused("Upload is paused");
                          }
                      }
                  });
              }
              else
              {
                  hideProgressDialog();
                  Log.e(TAG, "Upload file does not exists");
                  if (firebaseUploadCallback!=null)
                  {
                      firebaseUploadCallback.onFirebaseUploadFailure("Upload file does not exists");
                  }
              }
          }else
          {
              hideProgressDialog();
              Log.e(TAG,"pathToFile cannot be null or empty");
              if (firebaseUploadCallback!=null)
              {
                  firebaseUploadCallback.onFirebaseUploadFailure("pathToFile cannot be null or empty");
              }
          }
      }
      

      如下调用此方法:

      public void uploadDummyPicture(String email, String imagePath){
          if (imagePath == null) {
              return;
          }
          if (!isValidEmail(email)) {
              return;
          }
          String serverFolder = "dummy_images/" + email; //path of your choice on firebase storage server
          String fileName = "DummyPhoto.png";
          uploadFile(imagePath, fileName, serverFolder, "image/png");
          showProgressDialog();
      }
      

      确保在使用上述代码之前检查firebase storage 规则,如here 所述。如果规则需要firebase身份验证,则先完成当前用户的firebase authentication,然后开始上传文件。

      希望这个回答能解决你的问题。

      【讨论】:

      • 您好,感谢您的回复。我还无法测试您的回复,在下面我找到了一个使用与我类似的代码的答案。所以我不知道它是否会起作用。最好的问候和成功!
      【解决方案4】:

      就我而言,我在 onActivityResult 函数中获取的 URI 的格式不正确。 以前我是这样解析的

      uri=Uri.parse(your image path)
      

      但是改成这个之后就可以了

      uri=Uri.fromFile(new File(your image path))
      

      上传功能

      public void upload()
          {
              if(uri!=null)
              {
      
                  progressBar.setVisibility(View.VISIBLE);
                  progressBar_tv.setVisibility(View.VISIBLE);
                  Log.i("URI",uri.getPath());
                  UploadTask uploadTask=sRef.putFile(uri);
                  uploadTask.addOnFailureListener(new OnFailureListener() {
                      @Override
                      public void onFailure(@NonNull Exception e) {
                          Toast.makeText(VideoEditAndUploadActivity.this, "Upload Failed:"+e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                          e.printStackTrace();;
                      }
                  }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                      @Override
                      public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                          Toast.makeText(VideoEditAndUploadActivity.this, "Upload Successful!", Toast.LENGTH_SHORT).show();
                          progressBar.setVisibility(View.INVISIBLE);
                          progressBar_tv.setVisibility(View.INVISIBLE);
                      }
                  }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                      @Override
                      public void onProgress(@NonNull UploadTask.TaskSnapshot snapshot) {
                          updateUploadProgress(snapshot);
                      }
                  });
              }
              else{
                  Toast.makeText(this, "Video Uri is null: please choose a video first!", Toast.LENGTH_SHORT).show();
              }
          }
      

      更新进度条功能

      @SuppressLint("DefaultLocale")
          private void updateUploadProgress(UploadTask.TaskSnapshot snapshot) {
              long fileSize=snapshot.getTotalByteCount();
              long uploadBytes=snapshot.getBytesTransferred();
              long progress=(100*uploadBytes)/fileSize;
      
              progressBar.setProgress((int) progress);
              progressBar_tv.setText(String.format("%d%%", progress));
          }
      

      【讨论】:

        【解决方案5】:

        如果你使用的是 rxjava 那么你可以使用下面的 sn-p

        public Observable<FirebaseFile> uploadImageToFirebase(@NonNull Uri file) {
                return Observable.create(emitter -> {
                    try {
                        final StorageReference conversationReference = reference.child("some-identifier");
                        final File localFile = new File(file.getPath());
                        final StorageReference fileReference = conversationReference
                                .child(UUID.randomUUID().toString().toLowerCase(Locale.ROOT) + "-" + localFile.getName());
                        final UploadTask uploadTask = fileReference.putFile(file);
                        uploadTask.continueWithTask(task -> {
                            if (task.isSuccessful()) {
                                return fileReference.getDownloadUrl();
                            } else {
                                if (task.getException() != null) {
                                    throw task.getException();
                                } else {
                                    throw new RuntimeException("Error uploading file to firebase storage");
                                }
                            }
                        }).addOnCompleteListener(task -> {
                            if (task.isSuccessful()) {
                                final Uri downloadUri = task.getResult();
                                if (downloadUri != null) {
                                    emitter.onNext(new FirebaseFile(file.getPath(), downloadUri.toString(), 100));
                                    emitter.onComplete();
                                } else {
                                    if (!emitter.isDisposed()) {
                                        emitter.onError(new RuntimeException("Error uploading stream to firebase storage"));
                                    }
                                }
                            } else {
                                if (!emitter.isDisposed()) {
                                    emitter.onError(new RuntimeException("Error uploading file to firebase storage"));
                                }
                            }
        
                        });
                        uploadTask.addOnProgressListener(taskSnapshot -> {
                            double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
                            emitter.onNext(new FirebaseFile(file.getPath(), null, (int) progress));
                        });
                    } catch (Exception e) {
                        if (!emitter.isDisposed()) {
                            emitter.onError(e);
                        }
                    }
                });
            }
        

        在哪里

        FirebaseStorage fs = FirebaseStorage.getInstance()
        

        StorageReference StorageReference = firebaseStorage.getReference("some-identifier-if-any");```
        

        【讨论】:

          猜你喜欢
          • 2017-09-18
          • 2017-03-20
          • 1970-01-01
          • 2019-02-11
          • 2018-06-05
          • 2020-03-21
          • 2017-09-25
          相关资源
          最近更新 更多