通过改造

时间:2016-02-09 15:55:37

标签: java android django request retrofit

我正在尝试将图片发送到我的服务器,我发现许多使用 TypedFile 的解决方案但现在已弃用,我尝试使用 RequestBody 但我的 JSON 似乎是空的,我使用 Django 作为后端框架,这是我的改装代码:

EndpointInterface service = ServiceAuthGenerator.createService(EndpointInterface.class);
    MediaType mediaType = MediaType.parse("multipart/form-data; boundary=---011000010111000001101001");
    RequestBody body = RequestBody.create(mediaType,file);
    //RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpg"), file);
    Call<JSONObject> call = service.uploadPhoto(body);
    call.enqueue(new Callback<JSONObject>() {

        @Override
        public void onResponse(Response<JSONObject> response, Retrofit retrofit) {
            Log.v("Upload->", response.message().toString());

        }

        @Override
        public void onFailure(Throwable t) {
            Log.e("Upload", t.getMessage());
        }
    });
}

谁能告诉我我做错了什么或我怎么做?谢谢! :d

编辑:

这是我的活动功能:

  public void sendPhoto(File file)
    {
        EndpointInterface service = ServiceAuthGenerator.createService(EndpointInterface.class);
        RequestBody fbody = RequestBody.create(MediaType.parse("image/*"), file);
        RequestBody namebody = RequestBody.create(MediaType.parse("text/plain"), "735064");
        Call<JSONObject> call = service.uploadPhoto(fbody,namebody);
        call.enqueue(new Callback<JSONObject>() {
            @Override
            public void onResponse(Response<JSONObject> response, Retrofit retrofit) {
                Log.v("Upload->", response.message().toString());
            }
            @Override
            public void onFailure(Throwable t) {
                Log.e("Upload", t.getMessage());
            }
        });
    }

这就是我将图像设置为imageView的方式:

builder.setTitle("Profile Photo");
        builder.setIcon(R.drawable.gallery2);
        builder.setAdapter(adapter,new DialogInterface.OnClickListener()

        {

            public void onClick (DialogInterface dialog,int item){
            if (item == 0) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                /*file = new File(Environment.getExternalStorageDirectory(),
                        "tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".png");*/
                file = new File(Environment.getExternalStorageDirectory(),"tmp_avatar.jpg");
                mImageCaptureUri = Uri.fromFile(file);

                try {
                    intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
                    intent.putExtra("return-data", true);

                    startActivityForResult(intent, PICK_FROM_CAMERA);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                dialog.cancel();
            } else {
                Intent intent = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.setType("image/*");
                startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
            }
        }
        }

        );
        final AlertDialog dialog = builder.create();




@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) return;

        Bitmap bitmap = null;


        if (requestCode == PICK_FROM_FILE) {
            mImageCaptureUri = data.getData();
            path = getRealPathFromURI(mImageCaptureUri); //from Gallery

            if (path == null)
                path = mImageCaptureUri.getPath(); //from File Manager*/

            if (path != null)
                bitmap = BitmapFactory.decodeFile(path);
        } else {
            path = mImageCaptureUri.getPath();
            bitmap = BitmapFactory.decodeFile(path);

        }
        final double viewWidthToBitmapWidthRatio = (double) mImageView.getWidth() / (double) bitmap.getWidth();
        mImageView.getLayoutParams().height = (int) (bitmap.getHeight() * viewWidthToBitmapWidthRatio);

        mImageView.setImageBitmap(bitmap);
    }

    public String getRealPathFromURI(Uri contentUri) {
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(contentUri, proj, null, null, null);
        if (cursor == null) {

            return null;
        }

        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

        cursor.moveToFirst();


        return cursor.getString(column_index);
    }

1 个答案:

答案 0 :(得分:0)

   public interface ApiInterface {
        @Multipart
        @POST ("/api/your/endpoint")
        Call<User> editProfile (@Header("Authorization") String authorization, @Part("file\"; filename=\"pp.png\" ") RequestBody file , @Part("name") RequestBody fname, @Part("Id") RequestBody id);
    }
  

&#34;文件\&#34;在@Part注释中是文件参数的名称和   &#34;文件名&#34;是要上传的文件的名称。

I executed the above request like this..

File file = new File(imageUri.getPath());
        RequestBody fbody = RequestBody.create(MediaType.parse("image/*"), file);
        RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "name");
        RequestBody id = RequestBody.create(MediaType.parse("text/plain"), "123456");
        Call<User> call = client.editProfile("AccessToken", fbody, name, id);
        call.enqueue(new Callback<User>() {
            @Override
            public void onResponse(retrofit.Response<User> response, Retrofit retrofit) {
                Log.d("Tag",response.body());
            }

            @Override
            public void onFailure(Throwable t) {
                t.printStackTrace();
            }
        });