FirebaseStorage不会上传图片

时间:2017-12-14 11:22:20

标签: android firebase firebase-storage

我想将图片上传到我的Firebase存储分区,但它总是从OnFailureListener返回一个值。

以下是代码:

public class AddProductFragment extends Fragment {
    private static final int IMAGE_REQUEST = 1;

    private ProgressDialog progressDialog;
    private Uri uri;
    private EditText mTitle,mPrice;
    private Button mBtn,mUpload;
    private ImageView mImage;
    private FirebaseStorage mStorageRef;
    private StorageReference mRef;

    public AddProductFragment() {
        mStorageRef = FirebaseStorage.getInstance();
        mRef = mStorageRef.getReference().child("images");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.add_product_fragment,container,false);
        find(v);
        onClick();
        return v;
    }

    private void find(View v) {
        mTitle = (EditText)v.findViewById(R.id.singleProductTitle);
        mPrice = (EditText)v.findViewById(R.id.singleProductPrice);
        mBtn = (Button) v.findViewById(R.id.addProductSelectImageBtn);
        mImage = (ImageView)v.findViewById(R.id.addProductImage);
        mUpload = (Button)v.findViewById(R.id.uploadBtn);
    }

    private void onClick() {
        mBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("image/*");
                startActivityForResult(Intent.createChooser(intent,"Select Picture"), IMAGE_REQUEST);

            }
        });

        mUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                progressDialog = new ProgressDialog(getActivity());
                progressDialog.setMax(100);
                progressDialog.setMessage("Uploading...");
                progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                progressDialog.show();
                progressDialog.setCancelable(false);

                String title = mTitle.getText().toString();
                String price = mPrice.getText().toString();
                if (!title.isEmpty() && !price.isEmpty()) {
                    Product product = new Product();
                    Uri file = Uri.fromFile(new File(getRealPathFromURI(uri)));
                    mRef.child("original").child(product.getStringId());

                    mRef.putFile(file).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                            double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
                            //sets and increments value of progressbar
                            progressDialog.incrementProgressBy((int) progress);
                        }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast.makeText(getActivity(), "Error uploading....", Toast.LENGTH_SHORT).show();
                            progressDialog.dismiss();
                        }
                    }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            Uri downloadUrl = taskSnapshot.getDownloadUrl();
                            Toast.makeText(getActivity(),"Upload successful",Toast.LENGTH_SHORT).show();
                            //TODO: redirect to the uploaded product;
                            progressDialog.dismiss();
                        }
                    });



                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == IMAGE_REQUEST && resultCode == RESULT_OK) {
            try {
                uri = data.getData();
                Bitmap bitmap = null;
                if(uri != null) {
                    try {
                        bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    mImage.setImageBitmap(bitmap);
                } else {
                    Toast.makeText(getActivity(), "Uri not found...", Toast.LENGTH_SHORT).show();
                }
            } catch (NullPointerException e) {
                e.getMessage();
            }

        }
    }

    private String getRealPathFromURI(Uri contentURI) {

        String thePath = "no-path-found";
        String[] filePathColumn = {MediaStore.Images.Media.DISPLAY_NAME};
        Cursor cursor = getActivity().getContentResolver().query(contentURI, filePathColumn, null, null, null);
        if(cursor.moveToFirst()){
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            thePath = cursor.getString(columnIndex);
        }
        cursor.close();
        return  thePath;
    }


}

以下是例外情况:

  

/com.example.cmd.pop E / StorageException:   /image-0-02-05-64dcdbd29d607a4421b258b2adbfb848cf3262ee096a8b0ab2dbecd22631feea-V.jpg:   打开失败:ENOENT(没有这样的文件或目录)

     

java.io.FileNotFoundException:   /image-0-02-05-64dcdbd29d607a4421b258b2adbfb848cf3262ee096a8b0ab2dbecd22631feea-V.jpg:   打开失败:ENOENT(没有这样的文件或目录)

1 个答案:

答案 0 :(得分:0)

无论如何我找到了解决方案,参考路径错了

构造函数中的更改

public AddProductFragment() {
    mStorageRef = FirebaseStorage.getInstance();
    mRef = mStorageRef.getReference().child("images/original/");
    mThumbRef = mStorageRef.getReference().child("images/thumb");
}

OnActivityResult

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == IMAGE_REQUEST && resultCode == RESULT_OK) {
            uri = data.getData();

            String title = mTitle.getText().toString();
            String price = mPrice.getText().toString();
            if (!title.isEmpty() && !price.isEmpty()) {
                Product product = new Product();
                StorageReference thumbRef = mRef.child(product.getStringId()).child(uri.getLastPathSegment());
                StorageReference imageRef  = mRef.child(product.getStringId()).child(uri.getLastPathSegment());

                imageRef.putFile(uri).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
                        Log.d(TAG, e.getMessage());
                    }
                }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        Uri downloadUrl = taskSnapshot.getDownloadUrl();
                        Toast.makeText(getActivity(), "Upload successful", Toast.LENGTH_SHORT).show();
                        //TODO: redirect to the uploaded product;
                    }
                });

                thumbRef.putFile(uri).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
                        Log.d(TAG, e.getMessage());
                    }
                }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        Uri downloadUrl = taskSnapshot.getDownloadUrl();
                        Toast.makeText(getActivity(), "Upload successful", Toast.LENGTH_SHORT).show();
                        //TODO: redirect to the uploaded product;
                    }
                });




            }

        }
}

并添加了清单

的权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>