2016-01-05 120 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

感謝它的工作。你能分享這個代碼的瀏覽器兼容性嗎? –