java - 将图像上传到 Firebase 存储

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



                                }

            }


        }}

最佳答案

当使用以下代码在 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);
        }
    });

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

关于java - 将图像上传到 Firebase 存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49557184/

相关文章:

android - phonegap Android 跨域不工作

firebase - 如何在 Firebase Functions shell 中运行 Pub-Sub 函数

java - 如何在黑莓中的 hfm 中对齐文本字段和按钮字段

Java GUI 隐藏 Windows 任务栏

java - while-else-循环

android - 测试权限和 Android 应用 list 文件

java - @ClassRule 适用于所有测试类

android - 闹钟不该响的时候响

ios - 使用来自 GoogleService-Info.plist 的信息访问 Firebase 前端

firebase - 错误: reCAPTCHA container is either not found or already contains inner elements