由于jQuery的ajax函數(shù)锐极、及ajaxSubmit等函數(shù)的返回類型(dataType)只有xml盒齿、text、json枚荣、html等類型碗脊,沒有“流”類型,故我們要實(shí)現(xiàn)ajax下載時(shí)橄妆,不能夠使用相應(yīng)的ajax函數(shù)進(jìn)行文件下載衙伶。
請(qǐng)看實(shí)例:
1. form?通過js生成一個(gè)form,用這個(gè)form提交參數(shù)害碾,并返回“流”類型的數(shù)據(jù)矢劲。在實(shí)現(xiàn)過程中,頁(yè)面也沒有進(jìn)行刷新? 缺點(diǎn):無法傳遞header
?var form = $('<form>');
? ? ? ? ? ? ? ? ? ? form.attr('style','display:none');?
? ? ? ? ? ? ? ? ? ? form.attr('method','post');?
? ? ? ? ? ? ? ? ? ? form.attr('target', '_self');?
? ? ? ? ? ? ? ? ? ? form.attr('action',url);
? ? ? ? ? ? ? ? ? ? for (var obj in data) {
? ? ? ? ? ? ? ? ? ? ? ? if (data.hasOwnProperty(obj)) {
? ? ? ? ? ? ? ? ? ? ? ? ? ? var input =? $('<input>');
? ? ? ? ? ? ? ? ? ? ? ? ? ? input.attr('tpye','hidden');
? ? ? ? ? ? ? ? ? ? ? ? ? ? input.attr('name',obj);
? ? ? ? ? ? ? ? ? ? ? ? ? ? input.attr('value', data[obj]);
? ? ? ? ? ? ? ? ? ? ? ? ? ? form.append(input)
? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? $('body').append(form);
? ? ? ? ? ? ? ? ? ? form.submit();?
? ? ? ? ? ? ? ? ? ? form.remove();
2.axios? ?axios ie9+? ?? ? window.navigator.msSaveBlob ie10+? 此方法只兼容ie10+
var config = {
? ? ? ? ? ? headers: {
? ? ? ? ? ? ? ? 'token': token,
? ? ? ? ? ? ? ? 'Content-Type': 'multipart/form-data',
? ? ? ? ? ? },
? ? ? ? ? ? responseType: 'blob',
? ? ? ? }
axios.post(url, data,config).then( res => {
????if ('download' in document.createElement('a')) { // 非IE下載
? ? ? ? ? ? ? ? ? ? var url = window.URL.createObjectURL(res.data)
? ? ? ? ? ? ? ? ? ? var link = document.createElement('a')
? ? ? ? ? ? ? ? ? ? link.style.display = 'none'
? ? ? ? ? ? ? ? ? ? link.href = url;
? ? ? ? ? ? ? ? ? ? link.download = fileName;
? ? ? ? ? ? ? ? ? ? document.body.appendChild(link)
? ? ? ? ? ? ? ? ? ? link.click();
? ? ? ? ? ? ? ? ? ? window.URL.revokeObjectURL(link.href) // 釋放URL 對(duì)象
? ? ? ? ? ? ? ? ? ? document.body.removeChild(link)
? ? ? ? ? ? ? ? ? } else { // IE10+下載
? ? ? ? ? ? ? ? ? ? window.navigator.msSaveBlob(res.data, fileName)
? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? }).catch( res => {
? ? ? ? ? ? ? ? ? ? ? ? console.log(res)
? ? ? ? ? ? ? ? ? ? })