Retrofit 2 beta2 无法进行分段上传

Retrofit 2 beta2 failed to do multipart upload

我正在使用 Retrofit beta2,但在分段上传时遇到了困难。我已经尝试了指定的代码 here。我可能在这里遗漏了一些东西。

public interface SendMediaApiService {
    @Multipart
    @POST(/api/v1/messages)
    Call<ApiResponse> upload(
            @Header("Authorization") String token,
            @Query("recipient_user_id") String userId,
            @Query("message") String message,
            @Part("name=\"photo\"; filename=\"selfie.jpg\" ") RequestBody file
    );
}

private void upload() {
    Retrofit retrofit = new Retrofit.Builder()
        // do some stuffs here


    File file = new File(filePath);
    RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
    Call<ApiResponse> call = service.upload(token, userId, msg, requestBody);

}

当我卷曲时

$ curl -v \
> -H "Authorization: Bearer TOKEN" \
> -F "photo=@/path/to/my/image.jpg" \
> http://domain.com/api/v1/messages?recipient_user_id=USER_ID&message=test

也许,你可以删除@Multipart

就这样,

@POST("/V2/image/{type}")
Call<ImageUrl> uploadImg(@Path("type") int type, @Body RequestBody image);

要创建RequestBody,您可以使用

    public static RequestBody createImageRequest(Bitmap bitmap) {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
    return new MultipartBuilder()
            .type(MultipartBuilder.FORM)
            .addFormDataPart("file", "test.png", RequestBody.create(MediaType.parse("image/png"), byteArrayOutputStream.toByteArray())).build();
}

当我使用@Multipart 请求时,图像文件将被放入请求正文中。不带@Multipart时,请求头中的文件。

小前言:我是链接博客的合著者post。

您的代码看起来基本不错。我们的测试代码与您的测试代码之间的一点区别是 @Part() RequestBody file 声明。我们的代码没有指定文件:

@Part("myfile\"; filename=\"image.png\" ") RequestBody file.

另一方面,在您的代码中是:

@Part("name=\"photo\"; filename=\"selfie.jpg\" ") RequestBody file.

我建议从声明中删除 name=\" 部分,然后重试。如果没有帮助,您的错误是什么?

我已经使用 Retroft 成功上传了图像文件。正如@peitek 所建议的那样,删除 name=\" 部分解决了这个问题。

对于那些遇到这个困难的人来说,下面的代码是有效的(至少对我来说是这样)。这可以作为您的参考。

interface SendMediaApiService {
    @Multipart
    @POST(/api/v1/messages)
    Call<ApiResponse> upload(
            @Header("Authorization") String token,
            @Query("recipient_user_id") String userId,
            @Query("message") String message,
            @PartMap Map<String, RequestBody> map
    );
}

private void upload() {
    Retrofit retrofit = new Retrofit.Builder()
    // do some stuffs

    Map<String, RequestBody> map = new HashMap<>();
    File file = new File(path);
    RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpeg"), file);
    map.put("photo\"; filename=\"" + file.getName() + "\"", requestBody);

    SendMediaApiService service = retrofit.create(SendMediaApiService.class);
    Call<ApiResponse> call = service.upload(token, userId, msg, map);
    call.enqueue(this);
}

source