image upload using multipart retrofit 2

2019-03-02 12:54发布

问题:

Actually, I'm new in this field.facing some problem during image upload.the process automatically suspended after some time.I am attaching my code below.Please anyone helps me to solve this problem.

ServerResponse.java

public class ServerResponse {

// variable name should be same as in the JSON response from PHP

@SerializedName("success")
boolean success;
@SerializedName("success_msg")
//@SerializedName("message")
String message;

String getMessage() {return message;
}

boolean getSuccess() {
    return success;
}
}

ApiClient.java

 public class ApiClient {



// public static final String BASE_URL="http://www.mytriangle.net16.net";
  public static final String BASE_URL="http://bsenterprise.in/webservice/";
 // public static final String BASE_URL = "http://mushtaq.16mb.com/";
private static Retrofit retrofit = null;
public static int unique_id;



public static Retrofit getClient() {
    if (retrofit==null) {
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
}
}

ApiService.java(Interface class)

public interface ApiService {


@Multipart

@POST("imageupload-1.php?")
//@POST("retrofit_example/upload_image.php")
Call<ServerResponse> uploadFile(
                                @Part MultipartBody.Part file1,
                               // @Part MultipartBody.Part file2,
                               //
                               // @Part("file") RequestBody name,
                               // @Part("serial_no") int serial_no);
                                @Part("serial_no") int serial_no);

}

MainActivity

public class MainActivity extends AppCompatActivity {

Button btnUpload, btnPickImage;
String mediaPath;
ImageView imgView1,imgView2;
String[] mediaColumns = { MediaStore.Video.Media._ID };
ProgressDialog progressDialog;

public static int choice;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    progressDialog = new ProgressDialog(this);
    progressDialog.setMessage("Uploading...");

    btnUpload = (Button) findViewById(R.id.upload);
    btnPickImage = (Button) findViewById(R.id.pick_img);
    imgView1 = (ImageView) findViewById(R.id.preview1);
    imgView2 = (ImageView) findViewById(R.id.preview2);

    choice=0;

    btnUpload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            uploadFile();
        }
    });

    imgView1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            choice=1;
            Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(galleryIntent, 0);
        }
    });

    imgView2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            choice=2;
            Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(galleryIntent, 0);
        }
    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    try {
        // When an Image is picked
        if (requestCode == 0 && resultCode == RESULT_OK && null != data) {

            // Get the Image from data
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            assert cursor != null;
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            mediaPath = cursor.getString(columnIndex);
            // Set the Image in ImageView for Previewing the Media
            if(choice==1) {
                imgView1.setImageBitmap(BitmapFactory.decodeFile(mediaPath));
                cursor.close();
            }

          /*  else if(choice==2) {
                imgView2.setImageBitmap(BitmapFactory.decodeFile(mediaPath));
                cursor.close();
            }  */

        } else {
            Toast.makeText(this, "You haven't picked Image/Video", Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
    }

}



// Uploading Image/Video
private void uploadFile() {
    progressDialog.show();

    // Map is used to multipart the file using okhttp3.RequestBody
    File file1 = new File(mediaPath);
   // File file2 = new File(mediaPath);

    // Parsing any Media type file
    RequestBody requestBody1 = RequestBody.create(MediaType.parse("image/*"), file1);
   // RequestBody requestBody2 = RequestBody.create(MediaType.parse("*/*"), file2);

    MultipartBody.Part fileToUpload1 = MultipartBody.Part.createFormData("file", file1.getName(), requestBody1);
   // MultipartBody.Part fileToUpload2 = MultipartBody.Part.createFormData("file", file2.getName(), requestBody2);

    RequestBody filename1 = RequestBody.create(MediaType.parse("text/plain"), file1.getName());
   // RequestBody filename2 = RequestBody.create(MediaType.parse("text/plain"), file2.getName());

    ApiService getResponse = ApiClient.getClient().create(ApiService.class);
   // Call<ServerResponse> call = getResponse.uploadFile(fileToUpload1);
    Call<ServerResponse> call = getResponse.uploadFile(fileToUpload1,24);

    Toast.makeText(MainActivity.this,String.valueOf(file1),Toast.LENGTH_LONG).show();
    call.enqueue(new Callback<ServerResponse>() {

        @Override
        public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) {
            ServerResponse serverResponse = response.body();
            if (serverResponse != null) {
                if (serverResponse.getSuccess()) {
                    Toast.makeText(getApplicationContext(), serverResponse.getMessage(),Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplicationContext(), serverResponse.getMessage(),Toast.LENGTH_SHORT).show();
                }
            } else {
                assert serverResponse != null;
                Log.v("Response", serverResponse.toString());
            }
            progressDialog.dismiss();
        }

        @Override
        public void onFailure(Call<ServerResponse> call, Throwable t) {

        }
    });
}

}

In Dependencies

compile 'com.android.support:appcompat-v7:26.+'
compile 'com.squareup.retrofit2:retrofit:2.0.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'

Manifest Permission

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

Android Monitor output

11-03 14:31:07.404 13163-13163/? D/TidaProvider: TidaProvider()
11-03 14:31:07.584 13163-13163/? W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
11-03 14:31:07.724 13163-13163/? I/ViewRootImpl: CPU Rendering VSync enable = true
11-03 14:31:07.724 13163-13184/? D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
11-03 14:31:07.734 13163-13163/? D/Atlas: Validating map...
11-03 14:31:07.744 13163-13163/? D/ActivityThreadInjector: clearCachedDrawables.
11-03 14:31:07.784 13163-13184/? I/Adreno-EGL: <qeglDrvAPI_eglInitialize:379>: EGL 1.4 QUALCOMM build: Nondeterministic_AU_msm8916_32_LA.BR.1.2.4_RB1__release_AU (Ic8ede1fb34)
                                           OpenGL ES Shader Compiler Version: E031.25.03.04
                                           Build Date: 12/10/15 Thu
                                           Local Branch: mybranch17178083
                                           Remote Branch: quic/LA.BR.1.2.4_rb1.30
                                           Local Patches: NONE
                                           Reconstruct Branch: NOTHING
11-03 14:31:07.784 13163-13184/? I/OpenGLRenderer: Initialized EGL, version 1.4
11-03 14:31:07.804 13163-13184/com.example.atanu.imageview D/OpenGLRenderer: Enabling debug mode 0
11-03 14:31:07.894 13163-13163/com.example.atanu.imageview I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@1b1dad79 time:103294123
11-03 14:31:14.813 13163-13163/com.example.atanu.imageview I/Timeline: Timeline: Activity_launch_request time:103300687
11-03 14:31:23.323 13163-13173/com.example.atanu.imageview W/art: Suspending all threads took: 9.429ms
11-03 14:31:24.283 13163-13163/com.example.atanu.imageview I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@1b1dad79 time:103310156
11-03 14:31:26.602 13163-13163/com.example.atanu.imageview I/Choreographer: Skipped 34 frames!  The application may be doing too much work on its main thread.
11-03 14:31:27.292 13163-13163/com.example.atanu.imageview I/ViewRootImpl: CPU Rendering VSync enable = true
11-03 14:31:27.372 13163-13163/com.example.atanu.imageview I/Choreographer: Skipped 45 frames!  The application may be doing too much work on its main thread.
11-03 14:31:28.002 13163-13163/com.example.atanu.imageview I/ViewRootImpl: CPU Rendering VSync enable = true
11-03 14:31:28.012 13163-13163/com.example.atanu.imageview I/Choreographer: Skipped 37 frames!  The application may be doing too much work on its main thread.
11-03 14:31:29.292 13163-13163/com.example.atanu.imageview I/Choreographer: Skipped 75 frames!  The application may be doing too much work on its main thread.
11-03 14:31:29.342 13163-13184/com.example.atanu.imageview V/RenderScript: Application requested CPU execution
11-03 14:31:29.362 13163-13184/com.example.atanu.imageview V/RenderScript: 0xb83d1510 Launching thread(s), CPUs 4
11-03 14:31:29.992 13163-13163/com.example.atanu.imageview I/Choreographer: Skipped 40 frames!  The application may be doing too much work on its main thread.

回答1:

You should your file upload like this

      File file1 = new File(mediaPath);
    int id=24;
    // File file2 = new File(mediaPath);

    RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file1);
    MultipartBody.Part body = MultipartBody.Part.createFormData("photo", file.getName(), requestFile);

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


    ApiService getResponse = ApiClient.getClient().create(ApiService.class);
    // Call<ServerResponse> call = getResponse.uploadFile(fileToUpload1);
    Call<ServerResponse> call = getResponse.uploadFile(body,requestBodyid);

instead of

RequestBody requestBody1 = RequestBody.create(MediaType.parse("image/*"), file1);

EDIT: You have forgot to create request body for the id.add these to the code.

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

where id is your id,i.e id=24.



回答2:

If your problem is that progress bar is not getting hidden, you are not calling progressDialog.dismiss(); in onFailure function.