强制文件下载而不是显示在浏览器中

forced file to download instead showing in the browser

本文关键字:显示 浏览器 文件下载      更新时间:2023-09-26

我只是想下载文件时,按钮被点击。我在jQuery中使用top.location.href开始下载,但这段代码在本地主机上工作得很好,但是当我在服务器上尝试这个时,而不是开始下载它在浏览器中显示文件作为文本。

这就是我正在做的:

$('#download_button').click(function(){
    var filepath = $(this).attr("data-src");
    // filepath = library/files/filename.git
    top.location.href = filepath; // open download dialog box
});

上面的代码开始下载我的自定义文件,其中包含'xml'数据在本地主机上打开一个对话框,但这段代码不能在服务器上工作。

我做错了什么吗?

我试着找出问题,但每个人都说在你的hyaccess文件中添加这行代码

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

但是我从来没有在我的服务器上找到htaccess文件。

我可以在我的目录中创建一个新文件并添加以下代码吗?

试试这个代码

$('#download_button').click(function(){
    var filepath = $(this).attr("data-src");
    // filepath = library/files/filename.git
                                                                                               var url = 'library/files/download.php';
    var inputfied =  '<input type="text" name="filepath" value="' + filepath + '" />';
    var form = $('<form action="' + url + '" method="POST" >' +inputfied +'</form>');
    $('body').append(form);
    $(form).submit();
});

并使用此页面download.php

<?php
$file=$_POST['filepath'] ;//file location;
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: ' . filesize($file));
readfile($file);
?>

可以使用HTML5下载属性

<a href="/something.git" download="name-of-file">Click to download</a>