dragon012100
dragon012100
2018-03-21 07:31
浏览 129

图片上传API Call适用于Postman,但为什么不使用Android App?

I am trying to upload an image through API call from my app. But it seems to me that it is working in postman but not when done through my app. I am using retrofit 2 and backend code is PHP.Kindly help me through the process.

PHP Code:

case 'profileImage':

$id=$_POST['id'];
$image_name=("profile".$id.".jpg");
$upload_path=("../gm-app/assets/images/users-profile/".$image_name);

    $res= mysqli_query($db,"UPDATE `users` SET `image` = ('$image_name') WHERE `userid`='".$_POST['id']."'");

    if(isset($_FILES['file'])){

         if(move_uploaded_file($_FILES['file']['tmp_name'], $upload_path)){

            $rs['message'] = "Profile Image Updated";
            $rs['stat'] = "SUCCESS"; 
    }else{

        $rs['message'] = "Profile Image not Updated";
        $rs['stat'] = "FAILED";

    }
    }

echo json_encode($rs);die;
    break;

Retrofit call:

File file = new File(mediaPath);
        RequestBody requestBody=RequestBody.create(MediaType.parse("image/*"), file);
        Retrofit retrofit=new Retrofit.Builder().
                baseUrl(MyConstants.ROOT_URL).
                addConverterFactory(ScalarsConverterFactory.create()).
                build();

        apinterface services = retrofit.create(apinterface.class);
        Call<ResponseBody> call=services.postImage(requestBody,uid);

        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.body()!=null)
                {

                    try {

                        Toast.makeText(MyProfile.this, "Image Uploaded", Toast.LENGTH_SHORT).show();
                        String image =  response.body().string();

                        Log.d(TAG, "onResponse: "+image);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.d(TAG, "onFailure: "+t.getMessage());

            }
        });

API :

@Multipart
    @POST("services.php?apicall=profileImage")
    Call<ResponseBody> postImage(@Part("file") RequestBody image, @Part("id") String id);
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dsbj66959
    dsbj66959 2018-03-21 07:47
    已采纳

    Because there's something wrong with your code about multipart..

    Interface :

    @Multipart
    @POST("services.php?apicall=profileImage")
    Call<ResponseBody> postImage(
        @Part MultipartBody.Part image, 
        @Part("id") RequestBody id
    );
    

    Call the API

    Retrofit retrofit=new Retrofit.Builder().
            baseUrl(MyConstants.ROOT_URL).
            addConverterFactory(ScalarsConverterFactory.create()).
            build();
    apinterface services = retrofit.create(apinterface.class);
    
    //Bikin request body
    File file = new File(mediaPath);
    RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
    MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), reqFile);
    RequestBody reqId = RequestBody.create(MediaType.parse("text/plain"), uid);
    
    //Tembak APInya
    services.postImage(reqfile, reqId)
        .enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                //tulis aksi disini
            }
    
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                //tulis aksi disini
            }
    });
    
    点赞 评论
  • doudou1309
    doudou1309 2018-03-21 07:40

    Change the post method like this.

    @Multipart
    @POST(Urls.POST_A_QUERY)
    Call<CommonResponseModel> postAQuery(@Part("treatmentDetails") RequestBody treatmentDetails,@Part MultipartBody.Part file1);
    

    Then

     File file = new File(filePath);
     RequestBody requestFile = RequestBody.create(MediaType.parse(mediaType), file);
     document1 = MultipartBody.Part.createFormData("report1", Utils.getEdittextData(edtFirstFileName).concat(".jpg"), requestFile);
    

    Then pass that document1 value in second parameter.

     String mediaType = getActivity().getContentResolver().getType(uri);
                if (mediaType == null) {
                    mediaType = Utils.getMimeType(filePath);
                }
    

    Get mimetype function.

     public static String getMimeType(String url) {
        String type = null;
        String extension = MimeTypeMap.getFileExtensionFromUrl(url);
        if (extension != null) {
            type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        }
        return type;
    }
    
    点赞 评论

相关推荐