簡體   English   中英

無法使用AJAX下載文件

[英]File downloading using AJAX not working

我正在使用PHP中的AJAX創建簡單的文件下載腳本。 我的腳本不起作用。 表示點擊后在下載鏈接下方顯示pdf / doc文件的內容。 下圖將說明問題。

在此處輸入圖片說明



下面是我的代碼

AJAX和HTML

$(function() {
$(".download_link").click(function() {       
    var test = $("#content").val();
    var dataString = 'content='+ test;          
    $.ajax({
        type: "POST",
        url: "download_file.php",
        data: dataString,
        cache: false,
        success: function(html){            
        $("#display").after(html);
        document.getElementById('content').value='';            
    }
});
return true;
});
});

<a href="#" class="download_link" id="d_link">

PHP腳本:(download_file.php)

<?php     
ob_start();
$file = 'file.doc';
header("location:".$file);    
?>

您正在使用$("#display").after(html); 那就是為什么它顯示文件內容的原因。 您可以通過以下代碼下載文件。

$(function() {
$(".download_link").click(function() {       
    var test = $("#content").val();
    var dataString = 'content='+ test;          
    $.ajax({
        type: "POST",
        url: "download_file.php",
        data: dataString,
        cache: false,
        success: function(html){            
            window.location = 'your_file.pdf';
    }
});
return true;
});
});

我認為您的方法不正確。

使用您的腳本,您試圖將file.doc內容附加到DOM對象中->瀏覽器在AJAX請求上不知道如何管理文檔的編碼,它將不起作用。

對於下載文檔,我不會使用AJAX,如果您只打開帶有文檔url的新窗口並讓瀏覽器管理內容的響應,那會很好:

window.open("download_file.php");

如果您只想在同一頁面中顯示文檔內容,則可以使用iframe,如下所示:

<form action="download_file.php" method="GET" target="docIframe">
    <input type="submit" value="Download"/>
</form>

<iframe name="docIframe" width="600px" height="500px"/>
You need to set header content type to tell the browser how it renders the content for PDF or DOC.
<?php
   //Set header for pdf
    header("Content-type:application/pdf");
    header("Content-Disposition:attachment;filename='file_to_download.pdf'");
    readfile("original.pdf");
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM