无法在播放器中打开AJAX / Jquery MP3文件下载的文件

问题描述 投票:0回答:1

AJAX请求PHP脚本并下载MP3文件。下载提示会在客户端浏览器中弹出并下载文件,而不会出现问题。问题是下载的文件无法在播放器中打开。似乎该文件通过AJAX损坏或格式不正确。没有AJAX,所有的作品。怎么了?

PHP脚本

<?php

$mp3_file = 'song.mp3'; //the actual file you want to download

header('Content-Type: audio/mpeg');
header('Content-Disposition: attachment; filename='.basename($mp3_file));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($mp3_file));
readfile($mp3_file);
exit;
?>

JavaScript代码

$.ajax({
    url: "php-script.php",
    type: "POST",
    data: {"variableName" : 'some value'},
    dataType:"text",
    success: function (_data) {
        var blob = new Blob([_data]);
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.style.display = 'none';
        a.href = url;
        a.download = 'song.mp3'; // the filename you want to give
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
        alert('The download prompt was opened');
    },
    error: function() {
        alert('Something went wrong!');
    }
});
php jquery ajax http-headers mp3
1个回答
0
投票

媒体文件是二进制数据,但是您要告诉jQuery期待文本。

    dataType:"text",

我不记得jQuery是否可以像这样进行二进制响应。我没有在他们的文档中看到它。最好使用well-supported for years的Fetch API。

类似这样的东西:

const res = await fetch('php-script.php');
if (!res.ok) {
  // Throw error or something here
}
const blob = await res.blob();
© www.soinside.com 2019 - 2024. All rights reserved.