0

I want to upload multiple pdf files to my server. I am following this link for this purpose. My code is as following:

server_interface.java:

public interface server_interface {
    @Multipart
    @POST("server.php")
    Call<ResponseBody> uploadMultipleFilesDynamic(
        @Part List<MultipartBody.Part> files
    );
}

MainActivity.java:

server_interface api;

@Override
protected void onCreate(Bundle savedInstanceState) {
    List<MultipartBody.Part> parts = new ArrayList<>();
    for(Uri uri: list){
        parts.add(prepareFilePart(uri));
    }
    OkHttpClient.Builder httpClient = new OkHttpClient.Builder()
                .callTimeout(2, TimeUnit.MINUTES)
                .connectTimeout(2, TimeUnit.MINUTES)
                .readTimeout(3, TimeUnit.MINUTES)
                .writeTimeout(3, TimeUnit.MINUTES);

    Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(server_interface.JSONURL)
                .addConverterFactory(ScalarsConverterFactory.create())
                .client(httpClient.build())
                .build();

    api = retrofit.create(server_interface.class);
    Call<ResponseBody> uploadcall = api.uploadMultipleFilesDynamic(parts);
    if(uploadcall != null){
        uploadcall.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
            if(response.body() != null) {
                if (response.isSuccessful()) {
                    Toast.makeText(MainActivity.this, response.body().toString(), Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
                Log.d("response",t.toString());
            }
        });
    }
}
@NonNull
private MultipartBody.Part prepareFilePart(Uri fileUri) {
    File file = new File(fileUri.toString());
    Log.d("exists", String.valueOf(file.exists())); //shows false
    RequestBody requestFile =
                RequestBody.create(
                        MediaType.parse(getContentResolver().getType(fileUri)),
                        file
                );
    return MultipartBody.Part.createFormData("pdf", file.getName(), requestFile);
}

server.php:

<?php
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    header('Content-Type: text/plain; charset=utf-8');
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: POST, GET, OPTIONS');

    if(count($_FILES) > 0){
        $location = array();
        $folder="attachments/";
        for($i=0; $i<count($_FILES['file']['name']); $i++){
            if(!file_exists($folder.$_FILES['file']['name'][$i])){
                $moved = move_uploaded_file($_FILES['file']['tmp_name'][$i],$folder.$_FILES['file']['name'][$i]);
                if($moved){
                    if($i != count($_FILES['file']['name'])-1)
                        array_push($location,$folder.$_FILES['file']['name'][$i].';');
                    else
                        array_push($location,$folder.$_FILES['file']['name'][$i]);
                }
                else{
                    array_push($location,"Unable to upload");
                }
           }
           else{
                if($i != count($_FILES['file']['name'])-1)
                    array_push($location,$folder.$_FILES['file']['name'][$i].';');
                else
                    array_push($location,$folder.$_FILES['file']['name'][$i]);
           }
        }
        if(count($location) != 0){
           if(!in_array("Unable to upload",$location))
               echo json_encode($location);
           else
               echo "An attachment wasn't uploaded. Please try again. If issue persists, contact ITC/NFR/MLG";
        }
        else
           echo "Unable to upload";
    }
?>

When I execute my code, I keep getting an error in my onFailure():

java.io.FileNotFoundException: /document/document:1000011388: open failed: ENOENT (No such file or directory)

How do I fix this issue?

EDIT: This is how I am getting the uri

ActivityResultLauncher<Intent> intentresultlauncher = registerForActivityResult(
    new ActivityResultContracts.StartActivityForResult(),
        result -> {
            if (result.getResultCode() == Activity.RESULT_OK) {
                Intent data = result.getData();
                if(data != null){
                    Uri pdf_data = data.getData();
                    prepareFilePart(pdf_data);
                }
            }
        }
);
button.setOnClickListener(view -> {
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("application/pdf");
    intentresultlauncher.launch(intent);
});
  • You use a non existing impossible path. File.exists() would have told you already if you had used it before trying to upload. – blackapps Jun 13 '23 at 21:11
  • fileUri.getPath() gave you nonsense. Have a look at fileUri.toString() for a nice content scheme. – blackapps Jun 13 '23 at 21:13
  • Here it says otherwise https://stackoverflow.com/a/8370299/21917572 – abhishek_6198 Jun 14 '23 at 00:08
  • Yes, but that is irrelevant as it has nothing to do with your use case. And the 'path' is nonsense as you have seen. And you should have confirmed that File.exists() told you so. React to the point please. – blackapps Jun 14 '23 at 07:18
  • You're right, `file.exists()` shows false for all the files. But why? – abhishek_6198 Jun 14 '23 at 07:27
  • Repeat: because what you try to do is wrong. You just take a part of the content scheme. If you had seen a few file system paths before you would see immediately that you got an impossible path. You should use the whole content scheme. The whole uri. Uri.toString(). – blackapps Jun 14 '23 at 07:29
  • Yes, I tried `Uri.toString()` it keeps showing false – abhishek_6198 Jun 14 '23 at 07:32
  • Uri.toString() gives you a string. Not true or false. – blackapps Jun 14 '23 at 07:55

0 Answers0