使用retrofit2上传图片时出现Java.io.FileNotFoundException

标签 java android upload retrofit2

当我尝试使用retrofit2上传图片时,出现此错误

:java.io.FileNotFoundException(No such file or directory).

HashMap<String, RequestBody> partMap = new HashMap<>();
file = new File(draggablePresent.getImageUrls().valueAt(0))            
RequestBody fileBody = RequestBody.create(MediaType.parse("image/*"), file);
partMap.put("image\"; filename=\"" + file.getName() + "\"", fileBody);
compositeDisposable.add(iModelCustomer.uploadFiles(partMap)
              .subscribeOn(Schedulers.io())
              .observeOn(AndroidSchedulers.mainThread())
              .subscribe(new Consumer<String>() {
                  @Override
                  public void accept(String wcustomer) throws Exception {
                      Log.e("TAGgggg", wcustomer);

                  }
              }, new Consumer<Throwable>() {
                  @Override
                  public void accept(Throwable throwable) throws Exception {
                      Log.e("TAGpppp", throwable.toString());
                  }
              })
);

我收到错误:

E/TAGpppp: java.io.FileNotFoundException: file:/data/user/0/com.yaoyaodate.www.yaoyaodate/cache/cropped_1544702564825.jpg (No such file or directory)

我添加了这些代码:

Log.d("filepath",draggablePresent.getImageUrls().valueAt(0));
Glide.with(this).load(draggablePresent.getImageUrls().valueAt(0)).into(imgtest);
HashMap<String, RequestBody> partMap = new HashMap<>();
file = new File(draggablePresent.getImageUrls().valueAt(0));
Log.d("filename",file.getName());

我得到了正确的名字和照片。我可以通过 ADB shell 获取文件cropped_1544702564825.jpg。输出:

D/filepath: file:///data/user/0/com.yaoyaodate.www.yaoyaodate/cache/cropped_1544702564825.jpg D/filename: cropped_1544702564825.jpg

谷歌搜索了一整天也没解决。

有什么帮助吗?

我还添加了这些代码:

if(file.exists()){
                 Toast.makeText(this,""+file.getName(),Toast.LENGTH_SHORT).show();
            }

toast 不显示。如果文件不存在,为什么 getName 方法会输出正确的名称?我还添加了

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

这不起作用。

最佳答案

这可以工作,将“file:///”替换为“/”。

关于使用retrofit2上传图片时出现Java.io.FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53761825/

相关文章:

java - 监控分布在多台服务器上的一个应用程序

java - 生成的文件不会使用 Assembly Plugin 复制到 Maven 项目 zip 中

java - 如何使用 java 打开 .doc 或 .docx 文件并检查文本格式

android - 在 BOOT_COMPLETE 后在另一个线程中启动服务

image - 如何在 Google App Engine 中加载 Blobproperty 图像?

html - 文本链接而不是浏览表单

java - 如何在java中将字符串拆分为数字和字母

android - Admob child 定向设置

android - Bluestacks (HD-StartLauncher.exe) 通过命令提示符打开

upload - symfony2文件上传