首页 > 解决方案 > What's the use of Content-Type header when the response is an attachment?

问题描述

If the response header contains Content-Disposition: attachment; filename=image.gif, then the data will automatically be saved by the browser. Does passing Content-Type header make sense in such cases?

标签: htmlhttp-headers

解决方案


Yes it does make sense if you know the what the appropriate Content-Type header is, but NO it is not explicitly required.

RFC6266 Use of the Content-Disposition Header Field in HTTP
According to the original RFC 2616, the disposition type "attachment" only applies to content of type "application/octet-stream". But this restriction has been removed, because recipients in practice do not always check the content type, and it also discourages properly declaring the media type.

So traditionally, we used to have to always specify Content-Type:application/octet-stream to force a download, over time clients evolved and started ignoring it altogether if there was a disposition header header.

Content-Type tells the browser how to interpret the response, but Content-Disposition: attachment tells the browser to treat the response as a file, rather than trying to render it.

But not ALL clients are web browsers, and not all web browsers are equal. By providing the Content-Type as well then you are providing additional information that the client context can use if they choose to, or it will act as a default if for some reason the client does not understand or respect the disposition header, or its value.

By specifying the Content-Type many browsers will use this information to determine the file type restriction to apply on the Save As dialog, which is especially useful if you are NOT also specifying the file name.

Some modern web clients (and extensions for them) will inspect the Content-Type and choose to deliberately pass the content to application or extension that is registered for that type instead of always saving directly to file, even if the Content-Disposition is an attachment. You may have experienced this with PDF viewers.

There are also many older mobile web clients and mini-web browsers embedded within mobile apps that are known to not support Content-Disposition or they deliberately bypass it, instead forcing the content to be rendered directly, so by providing Content-Type when you can then you know that you are providing the most compatible output that you reasonably could.

There is a similar discussion on SO, but not directly a duplicate as this question asks why we might include it Content-Type knowing that it is not likely to be used.


推荐阅读