繁体   English   中英

通过改装将jpg发送到服务器

[英]sending jpg to server with 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);
    }
   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);
    }

@Part批注中的“ file \\”是文件参数的名称,“ filename”是将要上传的文件的名称。

 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();
            }
        });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM