处理后端响应的文件流

  1. // 下载文件
  2. export function downloadFile(stream, filename, filesSuffix) {
  3. console.log("stream instanceof Blob = ", stream instanceof Blob);
  4. let blob = new Blob([stream]);
  5. console.log("blob = ", blob); console.log('blob.type = ', blob.type);
  6. console.log('blob.type === application/octet-stream :', blob.type === 'application/octet-stream')
  7. /*stream必须为流Blob 流类型必须为 application/octet-stream */
  8. if (stream instanceof Blob && blob.type === 'application/octet-stream') {
  9. const url = window.URL.createObjectURL(blob)
  10. const link = document.createElement('a')
  11. link.href = url; link.style.display = 'none';
  12. // 解决ie浏览器不支持文件名包含“:”的问题
  13. // const fileName = name + '-' + parseTime(new Date(), '{y}-{m}-{d}') + '.' + suffix
  14. let fileName = ''
  15. if (filename) { fileName = fileName + filename }
  16. if (filesSuffix) { fileName = fileName + filesSuffix }
  17. link.setAttribute('download', fileName);
  18. document.body.appendChild(link);
  19. link.click();
  20. document.body.removeChild(link)
  21. } else {
  22. //流内容
  23. let fileReader = new FileReader();
  24. fileReader.onload = function() {
  25. //从内容中获取数据
  26. const res = JSON.parse(this.result);
  27. if (res && (res.code < 200 || res.code > 300)){
  28. //返回res状态异常,抛出原因!
  29. kr.ui.error(res.message || "下载失败!")
  30. }
  31. };
  32. fileReader.readAsText(blob);
  33. }
  34. }