強制文件下載而不是在瀏覽器裏打開顯示

Force Files to Download Instead of Showing Up in the Browser

強制文件下載而不是在瀏覽器裏打開顯示

 

Usually when a user goes goes to a file URL, the file will show in the browser if the browser supports it. Image files like png, gif, jpg almost always show in the browser. Archive files like zip, tar, and gzip almost are always downloaded. Some file types show up in some browsers but not others, svg files will display in Firefox and Safari, but not Internet Explorer 7. Internet Explorer will usually try to show Microsoft Word files (doc and docx) in the browser, while most other browsers will download it.

一般情況下用戶點擊文件連接,瀏覽器會直接打開文件而不是下載。不同的文件類型在不同的瀏覽器下會有不同的打開方式,具體的看上面的文字。

To add consistency or to force certain files to download, you can fix this by simply adding an .htaccess file to the files directory. Note this only works with Public downloads and an Apache web server.

要強制文件下載,簡單地在文件存放路徑加一個.htaccess文件即可(注:此方法只在apache服務器下,使用public downloads有效)。

 

  • First, setup your file field so that it saves into a separate directory. This will make it so that you will only force certain files to download and not affect the rest of the files on your Drupal site. Visit Administer -> Content management -> Content types (admin/content/types). Click "Manage fields" on the type that you want files to be forced to be downloaded. Add or edit a file field, under the "Path settings" fieldset, set a path for your files to be uploaded.

    Now files uploaded to that field will be saved in a separate folder under your sites files directory.

            首先,設置你的文件字段,讓它保存到一個獨立的目錄裏。

            Administer-->Content management -> Content types,點擊要設置下載的file字段後面的“管理字段”按鈕,在“設置路徑”那裏,設置一個供保存文件的獨立路徑。現在你的文件都保存在這個路徑下了

  • FTP to your site and create a file named .htaccess in your files directory. Usually this will be sites/default/files/[name of the subdirectory from step 1]. In that file put the following lines:

            這個路徑下增加一個.htaccess文件,裏面加如下內容:

<FilesMatch "\.(?i:doc|odf|pdf|rtf|txt)$">
  Header set Content-Disposition attachment
</FilesMatch>

 

This particular example will force files with doc, odf, pdf, rtf, or txt to download instead of being shown in the browser.

上面這個特例將強制doc, odf, pdf,rtf,txt這幾類文件將被下載而不是在瀏覽器裏打開。

上面的文件類別只是示例,你可以改成你自己的文件類型。

 

  • Upload a few files and (using the "Generic files" display setting), the files will be downloaded when the user clicks on the link.

            上傳一個文件,並設置顯示方式爲“普通文件”,用戶點擊這個文件連接的時候將直接下載而不是在瀏覽器裏打開了

  • You may need to load mod_headers in Apache2 for this to work.
    Assuming you have root access it can be done as follows:

            你可能需要在apache2里加裁mod_headers這個模塊。

            假設你的權限,按下面這樣做:

# a2enmod headers
# /etc/init.d/apache2 reload

 

原文地址:https://drupal.org/node/417866

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章