【问题标题】:FirebaseStorage wont upload imageFirebaseStorage 不会上传图片
【发布时间】:2017-12-14 11:22:20
【问题描述】:

我想将图片上传到我的 Firebase Storage 存储桶,但它总是返回来自 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(没有这样的文件或目录)

【问题讨论】:

  • 好吧,OnFailureListener 有一个例外 - 您在代码中完全忽略了它。你看过那个例外吗?我希望它能提供有关问题所在的有用信息。
  • @JonSkeet 我已经更新了帖子。
  • 好吧,听起来你应该调查一下 - 如果找不到本地文件,那并不是真正的 Firebase 问题。

标签: android firebase firebase-storage


【解决方案1】:

反正我找到了解决办法,参考路径是错误的

构造函数的变化

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"/>

【讨论】:

    猜你喜欢
    • 2021-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-02
    • 2023-03-19
    • 1970-01-01
    • 2020-01-29
    • 1970-01-01
    相关资源
    最近更新 更多