前端數據流文件下載三種方式

1、直接使用get請求方式進行下載

window.open(`${url}?${qs.stringify(param)}`, '_blank');

2、使用form 表單post請求進行下載:

const postDownloadFile = (action, param) => {
    const form = document.createElement('form');
    form.action = action;
    form.method = 'post';
    form.target = 'blank';
    Object.keys(param).forEach((item) => {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = item;
        input.value = param[item];
        form.appendChild(input);
    });
    document.body.appendChild(form);
    form.submit();
    document.body.removeChild(form);
}

postDownloadFile(url, param);

3、axios(ajax)前端根據返回數據流生成文件下載:

axios.post(url, param, {
  responseType: 'blob'
}).then((res) => {
  console.log('res', res);
  const blob = res.data;
  const reader = new FileReader();
  reader.readAsDataURL(blob);
  reader.onload = (e) => {
    const a = document.createElement('a');
    a.download = `文件名稱.zip`;
    // 後端設置的文件名稱在res.headers的 "content-disposition": "form-data; name=\"attachment\"; filename=\"20181211191944.zip\"",
    a.href = e.target.result;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  };
}).catch((err) => {
  console.log(err.message);
});
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章