在ajax调用完成后开始下载文件

3
$.ajax({
                    type: "POST",
                    url: "processform.php",
                    dataType: "json",
                    data: {name: name, email: email, city: city, country: country, day: day, month: month, year: year}
                    }).done(function(msg){

                        if(msg.success == 1){
                            $("#success_msg").append('<p>'+msg.message+'</p>');
                            window.location.href = './music/song.mp3';
                        }

                    });

以上代码只是加载一个带有音乐播放器的新页面。我希望它像下载文件一样下载。

4个回答

4
您可以通过PHP来实现,创建一个带有正确头部信息的PHP文件,然后重定向到该页面,这将强制浏览器下载该文件。
<?php
header('Content-disposition: attachment; filename=song.mp3');
header('Content-type: audio/mpeg3');
readfile('song.mp3');
?>

http_send_file来自pecl_http非常有用 - 它可以启用范围请求和http_match_etag以实现自动304(未修改)响应。请参阅http://php.net/manual/en/function.http-send-file.php和http://php.net/manual/en/function.http-match-etag.php。 - Olli

3

尝试按照以下方式操作:

header("Content-Disposition: attachment; filename=somefile.mp3;");

@Adam,在处理输出之前,设置内容类型为某种类型,以便浏览器可以下载。 - coder

2
如果您放弃在ajax调用后自动下载,那么可以这样做。浏览器会以自己的方式处理这种情况。
 $.ajax({
                type: "POST",
                url: "processform.php",
                dataType: "json",
                data: {name: name, email: email, city: city, country: country, day: day, month: month, year: year}
                }).done(function(msg){

                    if(msg.success == 1){
                        $("#success_msg").append('<p>'+msg.message+'</p>');
                       // window.location.href = './music/song.mp3';
                        $('<a/>', {target:'_blank', href:'./music/song.mp3'}).appendTo($("#success_msg")).html('Click To Download <Filename>');
                    }

                });

0

这取决于浏览器。如果您的浏览器有媒体插件,它可能会直接在浏览器中打开媒体文件,而不是提供下载对话框。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接