如何通过改造上传图片?

时间:2017-09-19 19:07:45

标签: android retrofit2 image-uploading

我查看过很多stackoverflow答案,但无法上传图片。它曾经给我@Multipart @POST("lostandfound") Call<ResponseBody> uploadLostAndFound(@PartMap Map<String, RequestBody> map); 。现在我找到了solution,但是它向服务器发送了一个空图像。你能告诉我我做错了吗?

这是我的请求代码

    Map<String, RequestBody> map = new HashMap<>();
    map.put("usermail", toRequestBody("mohammad_sed"));
    map.put("content", toRequestBody(content));
    map.put("islost", toRequestBody(String.valueOf(isLost)));
    map.put("wasfound", toRequestBody(foundPlace));
    map.put("tofind", toRequestBody(toFindPlace));

    File file = new File(destination);


    RequestBody reqFile = RequestBody.create(MediaType.parse("image"), file);
    MultipartBody.Part body = MultipartBody.Part.createFormData("upload", file.getName(), reqFile);
    map.put("img", body);

    ForumService client = Utils.getBuilder().create(ForumService.class);
    Call<ResponseBody> call = client.uploadLostAndFound(map);
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            if (response.isSuccessful()) {
                mProgressDialog.dismiss();
                // Toast.makeText(getApplicationContext(), "Request created", Toast.LENGTH_SHORT).show();
            } else {
                mProgressDialog.dismiss();
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            mProgressDialog.dismiss();
            Toast.makeText(getApplicationContext(), "Failed to upload!", Toast.LENGTH_SHORT).show();
        }
    });

    // This method  converts String to RequestBody
    public static RequestBody toRequestBody(String value) {
        RequestBody body = RequestBody.create(MediaType.parse("text/plain"), value);
        return body;
    }

我的 CALL

@Multipart
@POST("lostandfound")
Call<ResponseBody> uploadLostAndFound(@Part MultipartBody.Part photo,
                                      @PartMap Map<String, RequestBody> map);

我试过了:

Internal server error

但这样我得SELECT @@sql_mode
提前致谢。

1 个答案:

答案 0 :(得分:0)

找到了解决方案。我试过postman并且工作正常。

解决方案是我必须使用:

@Multipart
@POST("lostandfound")
Call<ResponseBody> uploadLostAndFound(@Part MultipartBody.Part photo,
                                  @PartMap Map<String, RequestBody> map);

RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("img", file.getName(), reqFile);

改变是我必须使用&#34; img&#34;而不是&#34;上传&#34;。这是一个愚蠢的错误:D