Issue
I am sending an image asset to be stored over HTTP and I want to carefully choose the MIME type.
Intuitively I would think that you want to follow the international standard and choose a MIME type that specifies the specific file format that is being sent. In fact, MIME sniffing is a technique that can be used to determine an asset's file format because this type aids the content consumer in processing the incoming data.
But, I am observing that popular web frameworks suggest that I handle files (including images) as multipart/form-data, for example expressjs recommends this, as does Flask.
Why would I choose to specify the MIME type as <type/subtype> multipart/form-data when the format image/subtype exists?
Solution
The mimetype of individual fields is separate from the mimetype of the message body which holds all the fields. multipart/form-data
is a standard way to encode multiple text and file parts from a form, send them as a single HTTP request, and have the server know how to parse it into the fields and files again. Each multipart item has a name and mimetype (content type). Flask parses all that for request.files
, each file is a FileStorage
instance.
image = request.files["image"] # image is the name of the field
print(image.filename)
print(image.content_type)
print(image.mimetype) # content type without encoding option
Browsers will detect the filename and mimetype from the file selected in a form input. Other clients (JavaScript, Python, etc.) usually have some mechanism to set this metadata for each file as well.
Most clients make it possible to send arbitrary bytes as the request body, and allow setting whatever mimetype is appropriate in that case. So if you want to send an image directly, you can do that too, but should only need to in very specialized cases.
Answered By - davidism
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.