Home > Mobile >  If there is a discrete MIME type for images, why is it common practice to send images as multipart/f
If there is a discrete MIME type for images, why is it common practice to send images as multipart/f

Time:07-16

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?

CodePudding user response:

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.

CodePudding user response:

I think you're confusing several concepts here.

If you have <form> on a web page that is going to upload data, and therefore has a <input type=file...> field, then the OVERALL format of the POST data has to be multipart/form-data. That data will consist of several subsections (as multipart does); each of the form fields will have their own individual MIME sections, and those sections should say image/jpeg, or whatever.

If you are sending data to the browser, then you should use the proper type.

  • Related