How to set dynamic filename?

2019-05-23 12:28发布

问题:

Using retrofit 2, how would I set a dynamic name for the uploaded file?

Currently, it's like this:

@Part("avatar\"; filename=\"image\" ") RequestBody image,

However, the uploaded file name would be image without the extension. Any recommendation on this case?

回答1:

Define your endpoint with MultipartBody.Part as the type:

interface Example {
  @Multipart //
  @POST("/foo/bar/") //
  Call<ResponseBody> method(@Part MultipartBody.Part part);
}

and then use its factories to create the type:

RequestBody body = // image body...
Call<ResponseBody> call = example.method(
    MultipartBody.Part.createFormData("image", "whatever.png", body));