781flyingdutchman / background_downloader

Flutter plugin for file downloads and uploads
Other
162 stars 76 forks source link

Allow specifying MIME type for form fields #371

Closed j-holsten closed 2 months ago

j-holsten commented 2 months ago

Is your feature request related to a problem? Please describe. In an upload request, I need to pass a multipart form data body with both a file and a JSON body in the following structure.

POST /upload HTTP/1.1
Content-Type: multipart/form-data; boundary=abcde12345

--abcde12345
Content-Disposition: form-data; name="address"
Content-Type: application/json

{
  "street": "3, Garden St",
  "city": "Hillsbery, UT"
}
--abcde12345
Content-Disposition: form-data; name="file"; filename="image1.png"
Content-Type: image/png

{…file content…}
--abcde12345--

When specifying the address as a form field (i.e. as fields: {'address': json.encode(address.toJson())}), the JSON body is always sent with Content-Type application/octet-stream, which is not accepted by the server. Even after looking through the documentation and the issues, I could not find a way to specify the MIME type of the form field or execute such a multipart request in any other way.

Describe the solution you'd like Ideally, it should also be possible to specify the MIME type for the form fields similar to the file upload, for example in the form of a map of fieldName -> (value, mimeType).

781flyingdutchman commented 2 months ago

Thanks. Adding the option to specify the mime-type is rather invasive (propagates through all of the communication between the plugin and the back-end. What if, instead, we improve the mime-type detection for the value of a field entry? Right now, the only detection done is to see if the value contains only plain ASCII characters. If so, there is no content ype set (which I imagine then defaults to 'application/octet-stream'). If not, content type is set to text/plain with content-transfer-encoding set to 'binary'.

The improvement would be:

The JSON test wold be simple: strip white space before and after, then detect braces {} or list [] characters at start and end, and if so the text is considered JSON.

Let me know what you think.

781flyingdutchman commented 2 months ago

Implemented as described in 8.5.4

j-holsten commented 2 months ago

Great idea! Thank you so much for implementing this so quickly!