195

我的网站上有一些大尺寸的 PDF 目录,我需要将它们链接为下载。当我用谷歌搜索时,我发现下面提到了这样的事情。它应该在链接单击时打开“另存为... ”弹出窗口...

 <head>
    <meta name="content-disposition" content="inline; filename=filename.pdf">
    ...

但它不起作用:/当我链接到如下文件时,它只是链接到文件并试图打开文件。

    <a href="filename.pdf" title="Filie Name">File name</a>

更新(根据下面的答案):

正如我所见,没有 100% 可靠的跨浏览器解决方案。可能最好的方法是使用下面列出的网络服务之一,并提供下载链接......

4

19 回答 19

288

从对Force a browser to save file as after click link的回答:

<a href="path/to/file" download>Click here to download</a>
于 2013-06-24T16:10:57.673 回答
90

使用该download属性,但要考虑到它仅适用于与您的代码同源的文件。这意味着用户只能下载来自源站点、同一主机的文件。

使用原始文件名下载:

<a href="file link" download target="_blank">Click here to download</a>

使用“some_name”作为文件名下载:

<a href="file link" download="some_name" target="_blank">Click here to download</a>

添加target="_blank"我们将使用一个新选项卡而不是实际选项卡,并且它还将有助于download属性在某些情况下的正确行为。

它遵循与同源策略相同的规则。您可以在MDN Web Doc 同源策略页面上了解有关此策略的更多信息

您可以在MDN Web Doc 锚的属性页面上了解有关此下载 HTML5 属性的更多信息。

于 2014-02-03T12:50:49.670 回答
35

元标记不是实现此结果的可靠方法。通常你甚至不应该这样做——应该由用户/用户代理来决定如何处理你提供的内容。如果他们愿意,用户可以随时强制他们的浏览器下载文件。

如果还想强制浏览器下载文件,直接修改HTTP头即可。这是一个 PHP 代码示例:

$path = "path/to/file.pdf";
$filename = "file.pdf";
header('Content-Transfer-Encoding: binary');  // For Gecko browsers mainly
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($path)) . ' GMT');
header('Accept-Ranges: bytes');  // Allow support for download resume
header('Content-Length: ' . filesize($path));  // File size
header('Content-Encoding: none');
header('Content-Type: application/pdf');  // Change the mime type if the file is not PDF
header('Content-Disposition: attachment; filename=' . $filename);  // Make the browser display the Save As dialog
readfile($path);  // This is necessary in order to get it to actually download the file, otherwise it will be 0Kb

请注意,这只是对 HTTP 协议的扩展;无论如何,某些浏览器可能会忽略它。

于 2010-09-27T09:45:30.923 回答
24

我遇到了同样的问题,并找到了一个到目前为止效果很好的解决方案。您将以下代码放入.htaccess文件中:

<FilesMatch "\.(?i:pdf)$">
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</FilesMatch>

它来自Force a File to Download 而不是 Showing Up in the Browser

于 2013-10-17T01:34:27.187 回答
11

我为 Firefox 找到了一个非常简单的解决方案(仅适用于相对而不是直接 href):添加type="application/octet-stream"

<a href="./file.pdf" id='example' type="application/octet-stream">Example</a>
于 2013-01-30T23:52:20.373 回答
7

尝试将此行添加到您的 .htaccess 文件中。

AddType application/octet-stream .pdf

我希望它能工作,因为它独立于浏览器。

于 2015-04-01T12:10:57.350 回答
7

一般是因为某些浏览器设置或插件直接在同一个窗口中打开PDF,就像一个简单的网页一样。

以下内容可能对您有所帮助。几年前我用 PHP 做过。但目前我不在那个平台上工作。

<?php
    if (isset($_GET['file'])) {
        $file = $_GET['file'];
        if (file_exists($file) && is_readable($file) && preg_match('/\.pdf$/',$file)) {
            header('Content-type: application/pdf');
            header("Content-Disposition: attachment; filename=\"$file\"");
            readfile($file);
        }
    }
    else {
        header("HTTP/1.0 404 Not Found");
        echo "<h1>Error 404: File Not Found: <br /><em>$file</em></h1>";
    }
?>

将以上内容另存为download.php

将这个小片段保存为服务器上某处的 PHP 文件,您可以使用它在浏览器中下载文件,而不是直接显示。如果您想提供 PDF 以外的文件,请删除或编辑第 5 行。

你可以像这样使用它:

将以下链接添加到您的 HTML 文件。

<a href="download.php?file=my_pdf_file.pdf">Download the cool PDF.</a>

参考自:本博客

于 2010-09-27T09:42:14.673 回答
7

我刚用过这个,但我不知道它是否适用于所有浏览器。

它适用于 Firefox:

<a href="myfile.pdf" download>Click to Download</a>
于 2018-01-05T08:25:54.220 回答
5

实现此目的的一种非常简单的方法是,无需使用外部下载站点或修改标题等,只需创建一个包含 PDF 的 ZIP 文件并直接链接到该 ZIP 文件。这将始终触发“保存/打开”对话框,并且人们仍然可以轻松双击与 .zip 关联的程序启动的 PDF 窗口。

顺便说一句,很好的问题,我也在寻找答案,因为大多数嵌入浏览器的 PDF 插件需要很长时间才能显示任何内容(并且在加载 PDF 时通常会挂起浏览器)。

于 2010-11-12T03:53:31.617 回答
5

只需将以下代码放入您的.htaccess文件中:

AddType application/octet-stream .csv
AddType application/octet-stream .xls
AddType application/octet-stream .doc
AddType application/octet-stream .avi
AddType application/octet-stream .mpg
AddType application/octet-stream .mov
AddType application/octet-stream .pdf

或者你也可以用 JavaScript 做诡计

element.setAttribute( 'download', whatever_string_you_want);
于 2016-03-04T19:10:45.017 回答
2

如果您需要强制下载页面上的单个链接,一个非常简单的方法是使用 href-link 中的 HTML5 下载属性。

见:http ://davidwalsh.name/download-attribute

有了这个,您可以重命名用户将下载的文件,同时强制下载。

这是否是一种好的做法一直存在争议,但就我而言,我有一个用于 PDF 文件的嵌入式查看器,并且该查看器不提供下载链接,因此我必须单独提供一个。在这里,我想确保用户不会在 Web 浏览器中打开 PDF,这会造成混淆。

这不需要打开另存为对话框,但会将链接直接下载到预设的下载目标。当然,如果您正在为其他人做一个网站,并且需要他们手动将属性写入他们的链接可能是一个坏主意,但如果有办法将属性放入链接,这可能是一个简单的解决方案。

于 2015-03-02T13:05:54.603 回答
2

服务器端解决方案更兼容,直到在所有浏览器中都实现了“下载”属性。

一个 Python 示例可以是文件存储的自定义 HTTP 请求处理程序。指向文件存储的链接生成如下:

http://www.myfilestore.com/filestore/13/130787e71/download_as/desiredName.pdf

这是代码:

class HTTPFilestoreHandler(SimpleHTTPRequestHandler):

    def __init__(self, fs_path, *args):
        self.fs_path = fs_path                          # Filestore path
        SimpleHTTPRequestHandler.__init__(self, *args)

    def send_head(self):
        # Overwrite SimpleHTTPRequestHandler.send_head to force download name
        path = self.path
        get_index = (path == '/')
        self.log_message("path: %s" % path)
        if '/download_as/' in path:
            p_parts = path.split('/download_as/')
            assert len(p_parts) == 2, 'Bad download link:' + path
            path, download_as = p_parts
        path = self.translate_path(path )
        f = None
        if os.path.isdir(path):
            if not self.path.endswith('/'):
                # Redirect browser - doing basically what Apache does
                self.send_response(301)
                self.send_header("Location", self.path + "/")
                self.end_headers()
                return None
            else:
                return self.list_directory(path)
        ctype = self.guess_type(path)
        try:
            f = open(path, 'rb')
        except IOError:
            self.send_error(404, "File not found")
            return None
        self.send_response(200)
        self.send_header("Content-type", ctype)
        fs = os.fstat(f.fileno())
        self.send_header("Expires", '0')
        self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
        self.send_header("Cache-Control", 'must-revalidate, post-check=0, pre-check=0')
        self.send_header("Content-Transfer-Encoding", 'binary')
        if download_as:
            self.send_header("Content-Disposition", 'attachment; filename="%s"' % download_as)
        self.send_header("Content-Length", str(fs[6]))
        self.send_header("Connection", 'close')
        self.end_headers()
        return f


class HTTPFilestoreServer:

    def __init__(self, fs_path, server_address):
        def handler(*args):
            newHandler = HTTPFilestoreHandler(fs_path, *args)
            newHandler.protocol_version = "HTTP/1.0"
        self.server = BaseHTTPServer.HTTPServer(server_address, handler)

    def serve_forever(self, *args):
        self.server.serve_forever(*args)


def start_server(fs_path, ip_address, port):
    server_address = (ip_address, port)
    httpd = HTTPFilestoreServer(fs_path, server_address)

    sa = httpd.server.socket.getsockname()
    print "Serving HTTP on", sa[0], "port", sa[1], "..."
    httpd.serve_forever()
于 2016-09-25T17:53:08.500 回答
2

这是旧帖子,但这是我在 JavaScript 中使用 jQuery 库的解决方案。

<script>
(function($){
    var download = [];
    $('a.force-download, .force-download a').each(function(){
        // Collect info
        var $this = $(this),
            $href = $this.attr('href'),
            $split = $href.split('/'),
            $name = document.title.replace(/[\W_]/gi, '-').replace(/-{2,}/g, '-'); // get title and clean it for the URL

        // Get filename from URL
        if($split[($split.length-1)])
        {
            $tmp = $split[($split.length-1)];
            $tmp = $tmp.split('.');
            $name = $tmp[0].replace(/[\W_]/gi, '-').replace(/-{2,}/g, '-');
        }

        // If name already exists, put timestamp there
        if($.inArray($name, download) > -1)
        {
            $name = $name + '-' + Date.now().replace(/[\W]/gi, '-');
        }

        $(this).attr("download", $name);
        download.push($name);
    });
}(jQuery || window.jQuery))
</script>

你只需要force-download在你的<a>标签中使用 class 并且会自动强制下载。您也可以将其添加到父级div,并将获取其中的所有链接。

例子:

<a href="/some/good/url/Post-Injection_Post-Surgery_Instructions.pdf" class="force-download" target="_blank">Download PDF</a>

这非常适合 WordPress 和任何其他系统或自定义网站。

于 2018-09-26T19:53:55.487 回答
1

添加响应头 Content-Disposition:attachment; 后跟文件名。删除 Meta Content-Disposition;Inline; 这将在同一窗口中打开文档

在java中它被设置为

response.setHeader("Content-Disposition", "attachment;filename=test.jpg");
于 2019-12-27T11:45:38.333 回答
0

在我添加的 HTML 代码中的文件名之后?forcedownload=1

这是我触发保存或下载对话框的最简单方法。

于 2015-04-23T16:00:43.727 回答
0

如果您在浏览器中有一个知道如何打开 PDF 文件的插件,它将直接打开。就像图像和 HTML 内容一样。

因此,另一种方法是不在响应中发送您的 MIME 类型。这样,浏览器将永远不知道应该打开哪个插件。因此它会给你一个保存/打开对话框。

于 2010-09-27T09:37:08.100 回答
0

Chrome 91 有一个新的变化,它支持 chrome 86-90 和 91+。以下语法将使它发生。

const fileHandle = await self.showSaveFilePicker({
   suggestedName: 'Untitled Text.txt',
   types: [{
      description: 'Text documents',
      accept: {
        'text/plain': ['.txt'],
      },
   }],
});

在这里阅读更多:

https://developer.chrome.com/blog/new-in-chrome-91/

**另一种解决方案,您可以将其制作为 blob,然后使用 saveAs **

const blob = fetch("some-url-here").then(data => data.blob());
saveAs(blob, "filename.txt")
于 2021-06-13T11:55:36.083 回答
0

我刚刚遇到了一个与添加的问题非常相似的问题,我需要在 ZIP 文件中创建指向文件的下载链接。

我首先尝试创建一个临时文件,然后提供了一个指向临时文件的链接,但我发现有些浏览器只会显示内容(CSV Excel 文件)而不是提供下载。最终我通过使用 servlet 找到了解决方案。它适用于 Tomcat 和 GlassFish,我在 Internet Explorer 10 和 Chrome 上尝试过。

servlet 将 ZIP 文件的完整路径名和应下载的 zip 文件名作为输入。

在我的 JSP 文件中,我有一个表格,显示 zip 中的所有文件,链接显示:onclick='download?zip=<%=zip%>&csv=<%=csv%>'

servlet 代码在 download.java 中:

package myServlet;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.zip.*;
import java.util.*;

// Extend HttpServlet class
public class download extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        PrintWriter out = response.getWriter(); // now we can write to the client

        String filename = request.getParameter("csv");
        String zipfile = request.getParameter("zip");

        String aLine = "";

        response.setContentType("application/x-download");
        response.setHeader( "Content-Disposition", "attachment; filename=" + filename); // Force 'save-as'
        ZipFile zip = new ZipFile(zipfile);
        for (Enumeration e = zip.entries(); e.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) e.nextElement();
            if(entry.toString().equals(filename)) {
                InputStream is = zip.getInputStream(entry);
                BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"), 65536);
                while ((aLine = br.readLine()) != null) {
                    out.println(aLine);
                }
                is.close();
                break;
            }
        }
    }
}

要在 Tomcat 上编译,您需要包含 tomcat\lib\servlet-api.jar 或在 GlassFish 上的类路径: glassfish\lib\j2ee.jar

但任何一个都适用于两者。您还需要将您的 servlet 设置为web.xml.

于 2017-06-09T15:37:13.380 回答
-2

对于大型 PDF 文件,浏览器会挂起。在 Mozilla 中,菜单ToolsOptionsApplications,然后在内容类型 Adob​​e Acrobat 文档旁边。在操作下拉列表中,选择始终询问

这对我不起作用,所以起作用的是:

菜单工具* →附加组件Adob​​e Acrobat(用于 Firefox 的 Adob​​e PDF 插件)→ 禁用。现在我可以下载电子书了!

于 2012-07-02T17:59:04.357 回答