使用Retrofit2 POST请求将图像上传到服务器

时间:2016-11-26 04:48:10

标签: android image-uploading multipartform-data retrofit2

我想使用Retrofit2将我的图库图像上传到服务器。 API有1个参数,其中包含flie作为表格数据&另一个参数是带键的标题。当我将图像上传到服务器时,我从服务器获得了File not found消息。我正在发送正确的文件名,但我不知道为什么这么做。任何人都可以帮我解决。下面是我的代码。

import { Component } from '@angular/core';
import { MenuController } from 'ionic-angular';

@Component({
  selector: 'page-dashboard',
  templateUrl: 'dashboard.html'
})

export class DashboardPage {    
  constructor(public menu: MenuController) {
    this.menu.enable(true, 'sidenav'); //'sidenav' is id of my <ion-menu>
    this.menu.open();
  }     
}

RetroClient.java

final ProgressDialog progressDialog;
        progressDialog = new ProgressDialog(UserProfileActivity.this);
        progressDialog.setMessage("Updating Data");
        progressDialog.show();

        //Create Upload Server Client
        ApiService service = RetroClient.getApiService();

        //File creating from selected URL
        File file = new File(imgDecodableString);
        Log.d("TAG","file="+file.getName());
        // create RequestBody instance from file
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);

        // MultipartBody.Part is used to send also the actual file name
        MultipartBody.Part body =
                MultipartBody.Part.createFormData("image", file.getName(), requestFile);

        Call<com.example.datamodel.Response> resultCall = service.uploadImage(loginHash,body);

        resultCall.enqueue(new Callback<com.example.datamodel.Response>() {
            @Override
            public void onResponse(Call<com.example.datamodel.Response> call, retrofit2.Response<com.example.datamodel.Response> response) {
                com.example.datamodel.Response mBean = response.body();
                if(null != mBean)
                {
                    Log.d("TAG","RS="+mBean.getMessage());
                    Log.d("TAG","RS="+mBean.getData().getvImage());
                }

                progressDialog.dismiss();
            }

            @Override
            public void onFailure(Call<com.example.datamodel.Response> call, Throwable t) {
                progressDialog.dismiss();
                Log.d("TAG", "fail=" + t.getMessage());
            }
        });

ApiService.java

public class RetroClient {
public RetroClient() {

}
private static Retrofit getRetroClient() {
    return new Retrofit.Builder()
            .baseUrl(AppConstants.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
}

public static ApiService getApiService() {
    return getRetroClient().create(ApiService.class);
}}

在logcat中,我从服务器收到File not found消息。有人请帮忙。提前谢谢。

1 个答案:

答案 0 :(得分:0)

尝试不使用多部分

 @POST("/api/name.jpg")
        Call<Object> upload(
                @Header("header_name") String authorization,
                @Body RequestBody body);

OnActivityREsult

      if (resultCode == Activity.RESULT_OK ) {

                Bitmap photo = null;
             if(requestCode==REQUEST_GALLERY){
                    try {
                        photo = MediaStore.Images.Media.getBitmap(getActivity().getApplicationContext().getContentResolver(), data.getData());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                // CALL THIS METHOD TO GET THE URI FROM THE BITMAP
                if(photo!=null){
                    Uri tempUri = getImageUri(getActivity(), photo);
                    // CALL THIS METHOD TO GET THE ACTUAL PATH
                    File finalFile = new File(getRealPathFromURI(tempUri));
                   RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
            apimy.upload(header value,requestBody).enque...            
                }
            }

 public Uri getImageUri(Context inContext, Bitmap inImage) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
        return Uri.parse(path);
    }

    public String getRealPathFromURI(Uri uri) {
        Cursor cursor = getActivity().getContentResolver().query(uri, null, null, null, null);
        assert cursor != null;
        cursor.moveToFirst();
        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
        return cursor.getString(idx);
    }

此代码适用于我。