Firebase Storage上传图片失败:未存入指定文件夹反而被命名为文件夹名
问题解决方法
问题根因
代码错误出在图片上传的StorageReference路径定义环节:你仅创建了指向Food/路径的引用,没有指定该文件夹下的具体文件名,因此上传操作直接将图片写入了Food这个路径,最终呈现为根目录下名为Food的文件,而非存入Food文件夹内。
修复方案
修改uploadtofirebase方法中的StorageReference定义逻辑,为Food文件夹下的文件指定自定义文件名即可,示例修改代码如下:
private void uploadtofirebase() { foodimg=(ImageView)findViewById(R.id.img_addfood); name=(EditText) findViewById(R.id.t4); calories=(EditText)findViewById(R.id.t1); proteins=(EditText)findViewById(R.id.t2); id=findViewById(R.id.t3); ProgressDialog dialog=new ProgressDialog(this); dialog.setTitle("File Uploader"); dialog.show(); // 先获取Food文件夹的根引用 StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("Food"); // 自定义文件名规则,示例:使用输入的食物ID + 时间戳 + .jpg 避免重名覆盖 String customFileName = id.getText().toString() + "_" + System.currentTimeMillis() + ".jpg"; // 生成最终的文件存储路径引用:Food/自定义文件名 StorageReference uploader = storageReference.child(customFileName); // 后续原有上传逻辑保持不变即可 uploader.putFile(filepath) .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { uploader.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() { @Override public void onSuccess(Uri uri) { FirebaseDatabase db=FirebaseDatabase.getInstance(); DatabaseReference root=db.getReference("list"); Calories obj=new Calories(name.getText().toString(),calories.getText().toString(),proteins.getText().toString(),uri.toString()); root.child(id.getText().toString()).setValue(obj); name.setText(""); calories.setText(""); proteins.setText(""); id.setText(""); foodimg.setImageResource(R.drawable.ic_launcher_background); Toast.makeText(getApplicationContext(), "uploaded", Toast.LENGTH_SHORT).show(); dialog.dismiss(); } }); } }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() { @Override public void onProgress(@NonNull UploadTask.TaskSnapshot snapshot) { float precent=(100*snapshot.getBytesTransferred())/snapshot.getTotalByteCount(); dialog.setMessage("Uploaded:"+(int)precent+"%"); } }); }
补充说明
- 文件名规则可以按需调整,比如直接用食物名称、原始上传文件名均可,只要在
Food文件夹引用后再调用child(文件名)指定具体文件路径即可。 - 加入时间戳是为了避免相同ID的文件上传时直接覆盖旧文件,如果不需要可以直接去掉时间戳部分。
内容的提问来源于stack exchange,提问作者john
相关产品推荐
相关产品推荐

