content-type of text-plain causes browser to downl

2019-04-19 18:20发布

I'm writing a web application API, where when someone accesses a URL, it returns text data. I set the content-type to "text/plain", but when I access it with Chrome, it downloads a file that contains the information, instead of displaying it. When I access it with IE, it shows properly, and when I access with Firefox, it says that it's attempting to access an application/octet-stream, and asking me if I want to download the file.

I recorded what was being returned by the web server using TinyHTTPProxy, and it's as follows:

[2012-03-11 16:51:45.345] INFO     {TinyHTTPProxy Thread-4} HTTP/1.1 200 OK
Content-Type: text/plain
Transfer-Encoding: chunked
Connection: close
Date: Mon, 05 Mar 2012 09:49:54 GMT
Server: localhost


[2012-03-11 16:51:45.345] INFO     {TinyHTTPProxy Thread-4} 10b
P,FIO,7,31.5900,0.,,0,100,0,0,30.7600,31.9600,100,1000,,,0.,16:03:14t,,0,31.5900    ,1.2,,,15,n,,,,,03/09/2012,,31.2200,,,,-0.37,-0.37,0.274456994,,,,,0,,2846732.85    ,14,4,,3989502,BSE-CSE-NYSE-PSE-NMS,,,,,0,,,0,1155872,N,,26,26,26,16:03:14,5-7-10-11-12-13-18-25-26-28-80,0

If I change the content-type to "application-json", then it displays on all browsers. Also, if I change the content-type to "text/html", it also works, even though I'm not returning an HTML file.

Is there an explanation why text/plain is behaving this way? I checked to make sure that all of the data being returned back is actually ASCII, and since I'm setting the content-type to be text/plain, I'm confused why it's being interpreted as application/octet-stream.

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-04-19 18:47

It sounds like you may be running into Chrome Issue 106150. Chrome apparently (sometimes) decides to use "sniffing" logic when the content-type is text/plain.

Possible workarounds:

  • If the text is Unicode, include a BOM. This will tell the sniffing logic that it really is text.
  • Remove "binary looking" bytes from the file. From the bug report "Any value between 0x00 and 0x1f looks binary except for ESC, CR, NP, NL, HT".
  • It sounds like using an extension that's obviously supposed to be text/plain (like .txt) might disable the sniffing.
查看更多
戒情不戒烟
3楼-- · 2019-04-19 18:56

Laurence's explanation is correct. Only IE and Chrome is performing mime sniffing at the time of this post. You can now just set the HTTP header X-Content-Type-Options: nosniff and it will do the trick!

查看更多
登录 后发表回答