将图像上传到firebase存储

时间:2018-03-29 13:20:38

标签: java android firebase firebase-storage

我正在尝试将从相机拍摄的图像上传到firebase存储,会出现一个消息对话框,但它会继续充电,并且没有图像上传到存储。 另外我想知道,我该如何取回特定用户发送的图像?我应该给图像提供图像的用户名,以便我可以用他的名字取回它吗?

public class ProfileActivity extends AppCompatActivity {
    public static final int CAMERA_REQUEST = 10;
    private LocationService service;
    private Button uploadbtn;
    private ImageView imgSpecimentPhoto;
    private ImageView imgSpecimentPhoto2;
    private ImageView imgSpecimentPhoto3;
    private StorageReference storage;
    private ProgressDialog mProgress;
    Uri photoURI;
    String mCurrentPhotoPath;
    private File createImageFile() throws IOException{
        //Create an image file name
        String timeStamp = new SimpleDateFormat( "yyyyMMdd_HHmmss" ).format( new Date());
        String imageFileName = "JPEG_" + timeStamp + "_.";
        File storageDir = getExternalFilesDir( Environment.DIRECTORY_PICTURES );
        File image = File.createTempFile(
                imageFileName,
                ".jpg",
                storageDir
        );
        mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }
    private void dispatchTakePictureIntent(){
        Intent takePictureIntent = new Intent (MediaStore.ACTION_IMAGE_CAPTURE);
        if(takePictureIntent.resolveActivity( getPackageManager())!= null){
            //Create the file where the photo should go
            File photoFile = null;
            try{
                photoFile = createImageFile();
            }catch (IOException ex){
                System.out.println("error taking the pic");
            }
            //Continue only if the file was successfull
            if(photoFile != null){
                photoURI = FileProvider.getUriForFile( this, "com.example.android.fileprovider",photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult( takePictureIntent, CAMERA_REQUEST );
            }
        }
    }


    private View currentView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile );
        service = new LocationService(this);
        uploadbtn = (Button) findViewById(R.id.upload);
        storage = FirebaseStorage.getInstance().getReference();
        mProgress = new ProgressDialog( this );

        //get access to the image view
        imgSpecimentPhoto = findViewById(R.id.camerabtn);
        imgSpecimentPhoto2 = findViewById(R.id.camerabtn5 );
        imgSpecimentPhoto3 = findViewById(R.id.camerabtn6);


        uploadbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mProgress.setMessage("Uploading...");
                mProgress.show();
                dispatchTakePictureIntent();


                    }
                } );



            }


    public void checkPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
                ) {//Can add more as per requirement

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
                    123);
        }
    }

    public void btnTakePhotoClicked(View v) {
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(cameraIntent, CAMERA_REQUEST);
        System.out.println("first");
        currentView= v;

    }

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


        //did the user chose okay
        if(requestCode == CAMERA_REQUEST && resultCode == RESULT_OK){

            //we are hearing back grom the camera
            Bitmap cameraImage = (Bitmap) data.getExtras().get( "data" );
            //now we have the image
            ImageView cur = (ImageView) currentView;
            cur.setImageBitmap( cameraImage );
            if (cur.getId() == imgSpecimentPhoto.getId()) {
                imgSpecimentPhoto2.setVisibility( View.VISIBLE );
            }
            if (cur.getId() == imgSpecimentPhoto2.getId()) {
                imgSpecimentPhoto3.setVisibility( View.VISIBLE );

            StorageReference filepath = storage.child("Photos").child( photoURI.getLastPathSegment());
            filepath.putFile( photoURI).addOnSuccessListener( new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    Toast.makeText(ProfileActivity.this, "Upload Successfull", Toast.LENGTH_SHORT).show();
                    mProgress.dismiss();

                }
            } ).addOnFailureListener( new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Toast.makeText( ProfileActivity.this, "Upload Failed", Toast.LENGTH_SHORT).show();
                }
            } );



                                }

            }


        }}

2 个答案:

答案 0 :(得分:1)

在代码下方使用Firebase上传图片时...

   bearImage.setDrawingCacheEnabled(true);
    bearImage.buildDrawingCache();
    Bitmap bitmap = bearImage.getDrawingCache();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] data = baos.toByteArray();

    // Upload it to our reference
    UploadTask uploadTask = bearRef.putBytes(data);
    buttonDownload.setEnabled(false);
    uploadTask.addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            // Handle unsuccessful uploads
            progressDialog.dismiss();

            Log.w(LOG_TAG, "Upload failed: " + exception.getMessage());
        }
    }).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();
            progressDialog.dismiss();

            Log.d(LOG_TAG, "Download Url: " + downloadUrl);
            buttonDownload.setEnabled(true);
        }
    });

删除上面代码中不需要的代码..

答案 1 :(得分:0)

关于使用用户名返回图片, 我会使用以下路径

将照片上传到存储空间
// storage/photos/users/userID/photoName
StorageReference storageReference = FirebaseStorage
                                   .getInstanace().getReference
                                   .child("photos/users/" + user_id +  "/photoName");

然后我会在数据库中创建一个照片节点,我会在其中添加 userID 然后添加图片。像这样的东西: 在这种特定情况下,我将用户的个人资料照片存储到数据库中。 ProfilePhoto模型只是个人资料图片网址。

ProfilePhoto profilePhoto = new ProfilePhoto(profile_img_url);
myRef.child("photos").child(user_id).child("photoName").setValue(profile_img_url);

通过这种方式,当我想要一些用户的照片时,我只是从数据库中获取指定用户ID的链接。