2016-01-05 57 views
0

我想从服务器下载文件,并且一旦用户完成下载操作,我想将其从服务器中删除。为此,我使用以下jquery插件: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文件的浏览器窗口,我得到以下错误:

Resource interpreted as Document but transferred with MIME type video/mp4.

左右,主要有问题:

  1. 每次失败回调方法被调用
  2. 记录浏览器的启动PLAY,而不是下载

或者,如果有其他方法可以实现这一点?感谢

回答

1

Or, If there is any other alternative way to achieve this? thanks

尝试使用XMLHttpRequestresponseType设置为"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(); 
+0

感谢您的回复。这个解决方案正在为我工​​作。 “onerror”回调有一些问题,因为它看起来没有用。我给服务器上不存在的文件的URL,但不是错误回调我在浏览器控制台上得到以下错误:“无法加载资源:服务器响应状态为404(未找到)” –

+0

尝试移动'console.log(“文件下载失败!”)''在'.onload'内的'else'声明 – guest271314

+0

感谢它的工作。你能分享这个代码的浏览器兼容性吗? –