浏览器打开 txt 文件乱码终极解决方案,亲测有效!

阅读: 评论:0

在点击如下链接的时候,浏览器会直接打开文件,而不是下载文件。

<a href=&#">点击下载</a>

问题就来了,当文件中包含中文等非ACCII编码字符,浏览器中预览就会乱码。

解决方案如下:

我们需要配置 nginx 或者 apache 服务器,明确 txt 文件的 content-type 和 charset

(1)nginx 配置

server {
    listen 80;
    server_name example;

    location / {
        root /path/to/your/files;
        charset utf-8;    # Ensure charset is specified as UTF-8
        autoindex on;     # Optional: enable directory listing
    }

    # Serve .txt files with the correct Content-Type
    location ~ .txt$ {
        default_type text/plain;
        charset utf-8;    # Ensure charset is specified as UTF-8
    }
}

(2)apache 配置

<VirtualHost *:80>
    ServerName example
    DocumentRoot /path/to/your/files

    # Ensure the default charset is set to UTF-8
    AddDefaultCharset UTF-8

    # Configure specific file types with UTF-8 charset
    <FilesMatch ".(txt)$">
        ForceType 'text/plain; charset=UTF-8'
    </FilesMatch>
</VirtualHost>

我的开源项目

  • course-tencent-cloud(酷瓜云课堂 - gitee仓库)
  • course-tencent-cloud(酷瓜云课堂 - github仓库)

本文发布于:2025-02-07 02:53:00,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/1738868002577596.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:乱码   浏览器   解决方案   文件   txt
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23