2

I am trying to upload all type of file to the server using okhttp3. I successfully uploaded files less than 2MB but for large files, uploading stops mid where. Code is

public void uploadfile(String filePath)
{
    File f = new File(filePath);
    String filepaths = f.getAbsolutePath();
    String content_type = getMimeType(f.getPath());
    OkHttpClient client = new OkHttpClient().newBuilder()
            .connectTimeout(10, TimeUnit.MINUTES)
            .readTimeout(15, TimeUnit.MINUTES)
            .writeTimeout(10, TimeUnit.MINUTES)
            .build();
    RequestBody fileBody = RequestBody.create(MediaType.parse(content_type),f);
    RequestBody body = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("type",content_type)
            .addFormDataPart("uploadedfile","nullify"+sourceFilePath.substring(sourceFilePath.lastIndexOf(".")),fileBody).build();
    RequestBody requestBody = ProgressHelper.withProgress(body, new ProgressListener() {
        @Override
        public void onProgressChanged(long numBytes, long totalBytes, float percent, float speed) {
            dialog.setProgress((int)(100 * percent));
        }
    });
    Request request = new Request.Builder()
            .url("https://Somewhere/save_file.php")
            .post(requestBody)
            .build();
    try {
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            response.close();
            dialog.dismiss();
        }
        if (!response.isSuccessful())
        {
            throw new IOException("Error:"+response);
        }


    } catch (IOException e) {
        e.printStackTrace();
    }
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Abhishek c
  • 539
  • 6
  • 16

0 Answers0