开发者

How to force a txt file to be read as an html document by browsers?

I have .txt files which are mostly (truly) html document (they have the header, body, html tags etc.). (I'm working in Windows environment here). I would like any browser to readily read them as html document (html document with normal .html suffix). Right now i have to rename the .txt file to be able to read it in the browser (Ex: myfile.txt -> myfile.txt.htm). Any trick we can apply to fool the browser right away?

Relative question: Is there any code i could add on top of those .txt file so that only .txt files with开发者_Python百科 that code will be open as html document and seen as such by browsers? (code could be anything added with hexadecimal editor ot plain ascii). Thanks.


Since you're reading the file directly off of your file system (ie: using a file: URL rather than http: or something else) your browser is using the extension to determine the content-type of the file. How this mapping from extension to content type is made varies from browser to browser (and also from OS to OS to a certain extent).

First off, I should say that I'd be a bit afraid of making this sort of change. There's probably lots of code that has a hard-coded assumption that .txt maps to text/plain, so altering that mapping is likely to expose all sorts of nasty bugs. Caveats aside, here's what you need to do:

In Firefox, ExternalHelperAppService is used to determine the type of file: URIs. Note that one of the steps is to use a hard-coded list of extension to type mappings, which most likely has .txt mapping to text/plain.

In IE the file type mappings come from OS settings. It varies a bit depending on which version of Windows you're dealing with, but usually in the same general part of the settings where you choose which program to run for each extension you can also set a mime-type for each extension. (This is also the place Firefox looks in the "the Operating System is asked for a MIME type" step mentioned on the page I linked to above, BTW.) If you sent the MIME type for .txt to text/html you should get the behavior you want.


It is the HTTP headers which tells your browser what kind of data it is transfering so you have to edit the settings of your web server


Save the text with its htm-codes in WORDPAD as OPEN Document text. Use in the name of the file the extension .htm. This worked for me.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜