繁体   English   中英

在第二个活动中如何在Firebase存储上上传图像?

[英]How to upload image on Firebase storage in my second activity?

请告诉我如何将图像上传到在第一次活动中捕获的Firebase 发送图像按钮后,按下的图像将进入第二个活动。 我可以在其中设置ImageView但不能将其上传到Firebase存储中。 请告诉我我错了。

这是我的第一次活动

  //camera
    camera=(ImageView)findViewById(R.id.cam);
    camera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            startActivityForResult(intent,CAMERA_REQUEST_CODE);
           // Intent intent = new Intent(Home.this,PostActivity.class);
           // startActivity(intent);
        }
    });


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode==CAMERA_REQUEST_CODE)

    {
        Uri uri=data.getData();
        Intent intent=new Intent(Home.this,PostActivity.class);
        intent.putExtra("imgUrl",uri.toString() );
        startActivity(intent);


    }
}

这是我的第二项活动

Bundle bundle = getIntent().getExtras();
    if (bundle != null) {
        // path = (Uri) bundle.get("imgUrl");
        path = Uri.parse(bundle.getString("imgUrl"));
        Log.e("ashish", path + "");

    }

    ImageView selfiiii = (ImageView) findViewById(R.id.mySelfie);
    selfiiii.setImageURI(path);



    btnPost.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {



            startPosting();
        }
    });
}

public void startPosting() {

    dialog.setMessage("posting....");
    dialog.show();
    final String status = WriteSomthng.getText().toString().trim();


    if (!TextUtils.isEmpty(status) && path!=null) {

        StorageReference filpath = reference.child("Posts").child(path.getLastPathSegment());
        Log.e("irfan sam",filpath+"");
        filpath.putFile(path).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                Uri downloadUrl = taskSnapshot.getDownloadUrl();
                DatabaseReference userPost = database.push();
                userPost.child("status").setValue(status);
                userPost.child("image").setValue(downloadUrl.toString());
                userPost.child("userName").setValue(Common.currentUser.getUserName());

                Intent intent = new Intent(PostActivity.this, Home.class);
                startActivity(intent);
                Toast.makeText(PostActivity.this, "Posted", Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }
        });


    }
}

您需要从图像路径为putFile(..)方法创建一个File 从Firebase中检查以下官方示例。

    // File or Blob
    file = Uri.fromFile(new File("path/to/mountains.jpg"));

    // Create the file metadata
    metadata = new StorageMetadata.Builder()
            .setContentType("image/jpeg")
            .build();

    // Upload file and metadata to the path 'images/mountains.jpg'
    uploadTask = storageRef.child("images/"+file.getLastPathSegment()).putFile(file, metadata);

    // Listen for state changes, errors, and completion of the upload.
    uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
            double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
            System.out.println("Upload is " + progress + "% done");
        }
    }).addOnPausedListener(new OnPausedListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onPaused(UploadTask.TaskSnapshot taskSnapshot) {
            System.out.println("Upload is paused");
        }
    }).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) {
            // Handle successful uploads on complete
            Uri downloadUrl = taskSnapshot.getMetadata().getDownloadUrl();
        }
    });

如果您在Uri有图片,则可以使用以下方法进行存储而无需进行转换:

private void uploadImage(Uri file) {
    if (file != null) {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("Uploading...");
        progressDialog.show();
        FirebaseStorage storage = FirebaseStorage.getInstance();
        StorageReference ref = storage.getReference().child("images/myPath/");
        ref.putFile(file)
            .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    progressDialog.dismiss();
                    Toast.makeText(FileUploadPage.this, "Uploaded", Toast.LENGTH_SHORT).show();
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    progressDialog.dismiss();
                    Toast.makeText(FileUploadPage.this, "Failed "+e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            })
            .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                    double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot
                              .getTotalByteCount());
                    progressDialog.setMessage("Uploaded "+(int)progress+"%");
                }
            });
    }
}  

要从Intent获取Uri ,可以使用如下代码:
在您的第一个活动中,您将Uri intent.putExtra("imgUrl", uri.toString());为: intent.putExtra("imgUrl", uri.toString());

然后在第二个活动中:

Intent intent = getIntent();
Uri path;
if (intent.hasExtra("imgUrl")) {
   path = Uri.fromFile(new File(getIntent().getStringExtra("imgUrl")));'
}
uploadImage(path);  

Uri.fromFile(new File(String path)应该可以防止Uri解码错误。

由于您具有路径,因此可以创建一个Uri并上传它

filpath.putFile(Uri.fromFile(new File("/sdcard/cats.jpg"))).addOnSuccessListener(....

另外,如果文件很大,则应创建Uri异步。

您应该添加FailureListener

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

这样,您可以查看上传的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM