Upload file in Retrofit 2

后端 未结 4 1802
谎友^
谎友^ 2020-12-29 12:35

I tried the following but on response i am getting 500 error (Internal Server Error) -- help me design the interface for the request in the above screenshot...thank

4条回答
  •  無奈伤痛
    2020-12-29 13:20

    The following code worked :)

     @Multipart
    @POST("myrecord")
    Call addRecord(@Query("token") String token, @Query("userid") int userId,
                                 @Query("name") String name, @Part MultipartBody.Part file);
    
    
    
     @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if ((requestCode == FILE_SELECT_CODE) && (resultCode == -1)) {
    
            File file = new File(getRealPathFromURI(data.getData()));
    
            RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), getRealPathFromURI(data.getData()));
    
            MultipartBody.Part multipartBody =MultipartBody.Part.createFormData("file",file.getName(),requestFile);
    
            Call responseBodyCall = service.addRecord(token, userId, "fileName", multipartBody);
            responseBodyCall.enqueue(new Callback() {
                @Override
                public void onResponse(Call call, Response response) {
                    Log.d("Success", "success "+response.code());
                    Log.d("Success", "success "+response.message());
    
                }
    
                @Override
                public void onFailure(Call call, Throwable t) {
                    Log.d("failure", "message = " + t.getMessage());
                    Log.d("failure", "cause = " + t.getCause());
                }
            });
    
        }
    }
    

提交回复
热议问题