Javascript 强制下载文件,而不是在浏览器中显示
我只想在点击按钮时下载文件。我正在使用jQuery中的Javascript 强制下载文件,而不是在浏览器中显示,javascript,php,jquery,html,Javascript,Php,Jquery,Html,我只想在点击按钮时下载文件。我正在使用jQuery中的top.location.href开始下载,但这段代码在本地主机上运行良好,但当我在服务器上尝试此操作时,它会在浏览器中将文件显示为文本,而不是开始下载 这就是我正在做的: $('#download_button').click(function(){ var filepath = $(this).attr("data-src"); // filepath = library/files/filename.git
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
});
上面的代码通过在localhost上打开一个对话框开始下载包含“xml”数据的自定义文件,但此代码在服务器上不起作用
我做错什么了吗
我试图找出问题所在,但每个人都说在hyaccess文件中添加这些代码行
<FilesMatch "\.(?i:git)$">
ForceType application/octet-stream
Header set Content-Disposition attachment
</FilesMatch>
ForceType应用程序/八位组流
标题集内容处置附件
但我从未在我的服务器上找到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();
});
只需创建一个新文件并将其命名为
.htaccess
。这就行了。它只是一个纯文本文件。理论上,你可以在目录中创建一个新的“.htaccess
”文件,是的。但是,如果web服务器中有多个.htaccess文件,则可能会导致意外情况。但是,请注意,并非所有浏览器都支持此属性。有关更多详细信息,请参阅。注意:此评论适用于任何试图使用此功能但不了解HTML5兼容性的人。
$('#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();
});
<?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);
?>