在Retrofit 2中上传文件

时间:2016-05-05 11:23:12

标签: android android-studio retrofit2

enter image description here

我尝试了以下但是在响应时我收到500错误(内部服务器错误) - 帮助我在上面的屏幕截图中设计请求的界面...谢谢

@Multipart
@POST("myrecord")
Call<ResponseBody> addRecord(@Query("token") String token,@Query("userid") int userId,
                             @Query("name") String name, @Part("file") RequestBody file);


File file = new File(getRealPathFromURI(data.getData()));
RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), getRealPathFromURI(data.getData()));` 
Call<ResponseBody> responseBodyCall = service.addRecord(token, userId,
                "newFileName", requestFile);
        responseBodyCall.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                Log.d("Response", "="+response.code());
                Log.d("Response", "= "+response.message());

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.d("failure", "message = " + t.getMessage());
                Log.d("failure", "cause = " + t.getCause());
            }
        });`

4 个答案:

答案 0 :(得分:10)

以下代码有效:)

 @Multipart
@POST("myrecord")
Call<ResponseBody> 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<ResponseBody> responseBodyCall = service.addRecord(token, userId, "fileName", multipartBody);
        responseBodyCall.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                Log.d("Success", "success "+response.code());
                Log.d("Success", "success "+response.message());

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.d("failure", "message = " + t.getMessage());
                Log.d("failure", "cause = " + t.getCause());
            }
        });

    }
}

答案 1 :(得分:3)

@Multipart
@POST("myrecord")
Call<ResponseBody> addRecord(@Part("file") RequestBody file,@Part MultipartBody.Part file,
@Query("token") String token,@Query("userid") int userId,@Query("name") String name);

RequestBody requestFile =
        RequestBody.create(MediaType.parse("multipart/form-data"), file);

MultipartBody.Part body =
        MultipartBody.Part.createFormData("picture", file.getName(), requestFile);


String descriptionString = "your description";

RequestBody description =
        RequestBody.create(
                MediaType.parse("multipart/form-data"), descriptionString);

有关更多信息,请查看以下链接: https://futurestud.io/blog/retrofit-2-how-to-upload-files-to-server

答案 2 :(得分:3)

如果您希望在不使用多部分的情况下将文件作为二进制文件发送到正文中,则可以从代码中删除@Multipart注释并使用@Body注释。它看起来像

@POST("myrecord")
Call<ResponseBody> addRecord(@Query("token") String token,@Query("userid") int userId,
                             @Query("name") String name, @Body RequestBody file);


File file = new File(getRealPathFromURI(data.getData()));
RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), getRealPathFromURI(data.getData()));
Call<ResponseBody> responseBodyCall = service.addRecord(token, userId,
                "newFileName", requestFile);
        responseBodyCall.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                Log.d("Response", "="+response.code());
                Log.d("Response", "= "+response.message());
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Log.d("failure", "message = " + t.getMessage());
            Log.d("failure", "cause = " + t.getCause());
        }
    });`

答案 3 :(得分:0)

    public String getRealPathFromURI(Context context, Uri contentUri) {
    Log.d("imin", "onClick: in image conversion");

    Cursor cursor = null;
    try {
        String[] proj = {MediaStore.Images.Media.DATA};
        cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        Log.d("imin", "onClick: in image conversion try");

        return cursor.getString(column_index);
    } finally {
        Log.d("imin", "onClick: in image conversion finally");

        if (cursor != null) {
            cursor.close();
        }
    }
}