Jquery下载文件插件不工作

时间:2016-01-05 14:58:48

标签: jquery jquery-plugins download resources mp4

我想从服务器下载文件,一旦用户完成下载操作,我想从服务器中删除它。因此,为此我使用以下Jquery插件:

  

fileDownload

我的想法是我将在其回调函数上删除文件。您可以在下面找到代码段:

 $.fileDownload(url, {
                contentType: "application/octet-stream",
                contentDisposition: 'attachment; filename=' + response.fileName
               })
               .done(function () {
                    console.log('File download a success!');
                })
               .fail(function () {
                    console.log('File download failed!');
                });

因此,当用户尝试下载文件时,主要发生以下错误:

  1. 每次调用 FAIL 回叫功能时,回拨功能都无法正常工作
  2. 尽管有FAIL回叫,但它没有下载文件,而是开始在浏览器窗口播放 MP4 文件,我收到以下错误:
  3.   

    资源解释为文档但使用MIME类型video / mp4传输。

    所以,主要有两个问题:

    1. 每次失败回调方法都称为
    2. 在浏览器上开始录制播放而不是正在下载
    3. 或者,如果还有其他替代方法可以实现这一目标吗?感谢

1 个答案:

答案 0 :(得分:1)

  

或者,如果还有其他替代方法可以实现这一目标吗?感谢

尝试将XMLHttpRequest设置为responseType

时使用"blob"
function refocus() {                     
  document.body.removeChild(document.getElementById("download"));
  console.log("File download a success!");
  window.removeEventListener("focus", refocus)
}

var request = new XMLHttpRequest();
request.open("GET", "/path/to/mp4", true); 
request.responseType = "blob";
request.onload = function (e) {
    if (this.status === 200) {
        // create `objectURL` of `this.response` : `.mp4` as `Blob`
        var file = URL.createObjectURL(this.response);
        var a = document.createElement("a");
        a.href = file;
        a.download = this.response.name || "file-" + new Date().getTime();
        a.id = "download";
        document.body.appendChild(a);
        a.click();
        // remove `a` following `Save As` dialog, 
        // `window` regains `focus`
        window.addEventListener("focus", refocus, false);

    } else {
        console.log("File download failed!")
    }
};
request.send();
相关问题