博客 / 詳情

返回

瀏覽器打開 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>

我的開源項目

酷瓜雲課堂-開源知識付費解決方案

  • course-tencent-cloud(酷瓜雲課堂 - gitee倉庫)
  • course-tencent-cloud(酷瓜雲課堂 - github倉庫)
user avatar
0 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.