强制使用ajax和php下载文件

时间:2015-04-22 06:46:01

标签: javascript php jquery ajax

我正在使用图片选择器插件来选择图像然后强制下载。我努力编写PHP,它按预期工作。下载弹出窗口,我设法查看该文件。我不确定为什么它在AJAX中不起作用。我错过了什么?

    //get the image-source or URL
    function getImageSrc()
    {
        var req = $("div[class='thumbnail selected']").children('img');
            var imagessource = []; 
                $(req).each(function (datakey, datavalue) {
                                src =  $(datavalue).attr('src'); 
                                        imagessource.push(src);
                                              }); 
                      return(imagessource);
    }

这是我点击按钮

的时候
 $("#download_media").click(function() {
                    var file = getImageSrc();    

                    $.ajax({
                        type: 'POST',
                        url: '?page=downloadController&action=downloadMedia',
                        data: {'file_url': file},
                        success: function(data) {
                            console.log("success");
                        }   
                    }); 
                });

我的PHP文件

 public function downloadMediaAction()
 {   
    //get the file_url
    $file = $this->getRequest()->('file_url');

    header("Content-Description: File Transfer"); 
    header("Content-Type: application/octet-stream"); 
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    readfile($file);
}

1 个答案:

答案 0 :(得分:0)

好的,然后从您的AJAX请求中返回要下载的文档的URL,如:

{'url':'http://server:port/path/to/file.php?id=x'}

然后使用javascript

document.location='http://server:port/path/to/file.php?id=x';

在file.php中

调用您的方法:public function downloadMediaAction()

要确保浏览器下载,请将此行添加到downloadMediaAction()

header("Content-Type: application/force-download");

相关问题