[英]forced file to download instead showing in the browser
我只是想在點擊按鈕時下載文件。 我在jQuery中使用top.location.href
開始下載,但是這個代碼在localhost上運行正常,但是當我在服務器上嘗試這個時,然后開始下載它在瀏覽器中將文件顯示為文本。
這就是我在做的事情:
$('#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>
但我從來沒有在我的服務器上找到htaccess文件。 我可以在我的目錄中創建一個新文件並將其添加到其中嗎?
您可以使用HTML5下載屬性
<a href="/something.git" download="name-of-file">Click to download</a>
試試這段代碼
$('#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);
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.