当“在浏览器中显示PDF”选项未选中时,是否有一种方法强制PDF文件在浏览器中打开?

我尝试使用嵌入标签和一个iframe,但它只有当该选项被选中时才会工作。

我该怎么办?


当前回答

如果你链接到一个。pdf文件,它会在浏览器中打开。 如果该框未选中,它应该链接到一个。zip以强制下载。

如果.zip文件不是一个选项,那么使用PHP中的头文件强制下载

header('Content-Type: application/force-download'); 
header('Content-Description: File Transfer'); 

其他回答

哎呀,我上一篇文章中有打字错误。

    header("Content-Type: application/force-download");
    header("Content-type: application/pdf");
    header("Content-Disposition: inline; filename=\"".$name."\";");

如果你不想让浏览器提示用户,那就用"inline"代替"attachment"作为第三个字符串。内联工作得很好。PDF立即显示,而不需要用户单击“打开”。我使用了“附件”,这将提示用户打开,保存。我尝试改变浏览器设置螺母,它不能阻止提示。

正确的格式是application/pdf,而不是application/force-download。这看起来像是对一些传统浏览器的黑客攻击。如果可以,总是使用正确的mimetype。

如果你可以控制服务器代码:

强制下载/提示:使用头(“Content-Disposition”,“附件;文件名= myfilename.myextension "); 浏览器尝试打开它:使用头("Content-Disposition", "inline;文件名= myfilename.myextension ");

无法控制服务器代码:

使用HTML5下载属性。它使用在视图端指定的自定义文件名。

注意:我更喜欢在服务器端设置文件名,因为您可能有更多的信息,可以使用公共代码。

虽然下面的工作很好在firefox,它不工作在chrome和移动浏览器。

Content-Type: application/pdf
Content-Disposition: inline; filename="filename.pdf"

要修复chrome和移动浏览器错误,请执行以下操作:

将文件存储在项目中的某个目录中 使用谷歌PDF查看器

谷歌PDF查看器可以这样使用:

<iframe src="http://docs.google.com/gview?url=http://example.com/path/to/my/directory/pdffile.pdf&embedded=true" frameborder="0"></iframe>

这是ASP的。NET MVC

在你的cshtml页面:

<section>
    <h4><a href="@Url.Action("Download", "Document", new { id = @Model.GUID })"><i class="fa fa-download"></i> @Model.Name</a></h4>
    <object data="@Url.Action("View", "Document", new { id = @Model.GUID })" type="application/pdf" width="100%" height="800" class="col-md-12">
        <h2>Your browser does not support viewing PDFs, click on the link above to download the document.</h2>
    </object>
</section>

在你的控制器中:

public ActionResult Download(Guid id)
    {
        if (id == Guid.Empty)
            return null;

        var model = GetModel(id);

        return File(model.FilePath, "application/pdf", model.FileName);
    }

public FileStreamResult View(Guid id)
    {
        if (id == Guid.Empty)
            return null;

        var model = GetModel(id);

        FileStream fs = new FileStream(model.FilePath, FileMode.Open, FileAccess.Read);

        return File(fs, "application/pdf");
    }

下面是在PHP中强制在浏览器中查看文件的另一种方法:

$extension = pathinfo($file_name, PATHINFO_EXTENSION);
$url = 'uploads/'.$file_name;
        echo '<html>'
                .header('Content-Type: application/'.$extension).'<br>'
                .header('Content-Disposition: inline; filename="'.$file_name.'"').'<br>'
                .'<body>'
                .'<object   style="overflow: hidden; height: 100%;
             width: 100%; position: absolute;" height="100%" width="100%" data="'.$url.'" type="application/'.$extension.'">
                    <embed src="'.$url.'" type="application/'.$extension.'" />
             </object>'
            .'</body>'
            . '</html>';