android – 在Retrofit 2中上传文件

前端之家收集整理的这篇文章主要介绍了android – 在Retrofit 2中上传文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我尝试了以下但是在响应时我得到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());
            }
        });`

解决方法

以下代码工作:)
@Multipart
@POST("myrecord")
Call<ResponseBody> addRecord(@Query("token") String token,@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,"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,"cause = " + t.getCause());
            }
        });

    }
}

猜你在找的Android相关文章