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

浏览器打开 txt 文件乱码解决方案

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

<a href="abc.txt">点击下载</a>

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

解决方案如下:

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

(1)nginx 配置

server {
    listen 80;
    server_name example.com;

    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.com
    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>

我的开源项目

酷瓜云课堂-开源知识付费解决方案

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值