0

How do you upload a video (.mp4) file in the raw folder to a server on a button click in java android studio with minSdk 29.

Any help with this would be much appreciated.

This is what I have tried:

private void configureUploadButton() {
        uploadButton = findViewById(R.id.uploadButton);
        uploadButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // creating a client
                OkHttpClient okHttpClient = new OkHttpClient();

                int videoResourceId = getResources().getIdentifier("name_of_video", "raw", getPackageName());
                Uri fileUri = Uri.parse("android.resource://" + getPackageName() + "/" + videoResourceId);
                Log.i("URI", "File URI: " + fileUri);

                File videoFile = new File(fileUri.getPath());
                Log.i("FILE_TAG", "File: " + videoFile + " Path: " + videoFile.getPath());

                RequestBody requestBody = RequestBody.create(MediaType.parse("video/mp4"), videoFile);
                MultipartBody multipartBody = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart("video", videoFile.getName(), requestBody)
                        .build();

                Request request = new Request.Builder()
                        .url("http://10.0.2.2:5000/upload_video")
                        .post(multipartBody)
                        .build();

                okHttpClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Log.i("SERVER_DOWN", "The sever is down: " + e.getMessage());
                                Toast.makeText(Record.this, "server down", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                int responseCode = response.code();
                                String responseMessage = response.message();
                                Log.i("RESPONSE", "Response code: " + responseCode + " Message: " + responseMessage);
                                if (response.isSuccessful()) {
                                    Toast.makeText(Record.this, "Connected to server successfully.", Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(Record.this, "Not able to connect to server.", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    }
                });
            }
        });
    }

I don't seem to be accessing the file correctly using the File class. The IOException that I am getting in the onFailure of the okHttpClient call is:

/2131689473: open failed: ENOENT (No such file or directory)

These are the permissions that I have in my Androidmanifest.xml

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.hardware.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
  • 1
    the way of getting video from raw and converting to file is wrong and that's why it is showing ```No such file or directory``` first you need to copy video from raw folder to device storage programmatically and then use path of file where you pasted in device you can copy file like this https://stackoverflow.com/a/8664527/5696047 – jayesh gurudayalani Feb 02 '23 at 05:45

1 Answers1

0

You will acces app data specific folder through " getExternalFilesDir() " and your application data available in " sdcard =>Android => package.name => file.mp4 "

APIClient.java

public class APIClient {

private static Retrofit retrofit = null;

public static Retrofit getClient(){
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient client = new OkHttpClient.Builder()
            .hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            })
            .addInterceptor(interceptor)
            .build();

    retrofit = new Retrofit.Builder()
            .baseUrl("http://10.0.2.2:5000")
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build();

    return retrofit;
}

}

APIInterface.java public interface APIInterface {

@Multipart
@POST("/api/UploadVideo")
Call<VideoUpload> chequeUpload(
                                @Part MultipartBody.Part video);

}

Model Class

public class VideoUpload {

 // Request
@SerializedName("video")
public String video;

// Response
  @SerializedName("Message")
  public String Message;

}

Upload video

video get from " Android " Specific folder sdcard =>Android => package.name => file.mp4

code.

   String root = getExternalFilesDir("/").getPath() + "/" + "Videos/";

   File videoFile = new File(root, "My_video" + ".mp4");

  RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), videoFile);

  MultipartBody.Part videoFileBody = MultipartBody.Part.createFormData("video", videoFile.getName(), requestFile);

    Call<VideoUpload> call = apiInterface.videoUploadNow(videoFileBody);

 call.enqueue(new Callback<VideoUpload>() {
        @Override
        public void onResponse(@NonNull Call<VideoUpload> call, @NonNull Response<VideoUpload> response) {
            pDialog.dismiss();
            if (response.isSuccessful()){
                VideoUpload uploadVideo = response.body();
             
             try {
                    JSONObject jsonObjectError = new JSONObject(response.errorBody().string());
                    showMessageInSnackbar(jsonObjectError.getString("Message"));
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }


            }else{
                try {
                    JSONObject jsonObjectError = new JSONObject(response.errorBody().string());
                    showMessageInSnackbar(jsonObjectError.getString("Message"));
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onFailure(@NonNull Call<VideoUpload> call, @NonNull Throwable t) {
            if(t instanceof SocketTimeoutException){
                timeOutDialog.show();
            }
            pDialog.dismiss();
        }
    });
Prasanth John
  • 146
  • 1
  • 4