xptrip
xptrip

Reputation: 59

Java.io.FileNotFoundException when using retrofit2 to upload images

When I tried to use retrofit2 to upload images, I got this error

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

I got the error:

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

I added these code :

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());

I got the correct name and the picture. I could get the file cropped_1544702564825.jpg through ADB shell. The output:

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

I searched on Google for whole day and couldn't solve it.

Any help?

I also add these codes:

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

The toast does't show. If the file doesn't exist, why does the getName method output the correct name? I also add

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

It doesn't work.

Upvotes: 0

Views: 945

Answers (1)

xptrip
xptrip

Reputation: 59

This can work, replace "file:///" with "/".

Upvotes: 2

Related Questions