Skip to content

[Java][retrofit2] file upload sets filename as baseName instead of a dynamic filename #7446

@acabarbaye

Description

@acabarbaye
Description

This is more a request to change formParams.mustache so that the filename can be set by the developer instead of defaulting to baseName.
In current template, the filename is set as follows:
okhttp3.MultipartBody.Part {{/usePlayWS}}{{^usePlayWS}}("{{baseName}}\"; filename=\"{{baseName}}") RequestBody
This way the filename is hardcoded and is the same for any file upload no matter what file is actually used. The reason for this is that the parameter is of RequestBody type. The solution to be able to make the filename in the request more dynamic is to use okhttp3.MultipartBody.Part instead as discussed there square/retrofit#1188. It is also described in the official documentation of retrofit2 https://futurestud.io/tutorials/retrofit-2-how-to-upload-files-to-server when it comes to file upload.

With such a change, when calling the endpoint the user would just need to do the following so that the filename is taken into account:
File dataFile;
String contentType;
final RequestBody body = RequestBody.create(contentType, dataFile.getFile());
return MultipartBody.Part.createFormData("datafile", dataFile.getFileName(), body);

Swagger-codegen version

Latest master: 2.3.1.

Suggest a fix/enhancement

I would thus propose the following change to formParams.mustache

{{#isFormParam}}{{#notFile}}{{#isMultipart}}@retrofit2.http.Part{{/isMultipart}}{{^isMultipart}}@retrofit2.http.Field{{/isMultipart}}("{{baseName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}{{#isMultipart}}@retrofit2.http.Part{{/isMultipart}}{{^isMultipart}}@retrofit2.http.Field{{/isMultipart}}{{#usePlayWS}} okhttp3.MultipartBody.Part {{/usePlayWS}}{{^usePlayWS}}() MultipartBody.Part {{/usePlayWS}}{{paramName}}{{/isFile}}{{/isFormParam}}

This would also require import okhttp3.MultipartBody; to be added to api.mustache

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions