问题描述:

前端通过jQuery ajax接受后端的文件流,前端下载文件后内容乱码

后端代码:

Header("Content-type: application/octet-stream");
Header("Accept-Ranges: bytes");

前端代码:

$.ajax({
  type: "POST",
  url: url,
  xhrFields: { responseType: "blob" },
  success: (response) => {
  const blob = new Blob(["\ufeff", response], {type: 'application/msword'});
  const blobUrl = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.style.display = 'none';
  a.href = blobUrl;
  a.target = '_blank';
  a.click();
  }
 })

word 文档内容乱码:


原因分析:

jQuery ajax response 类型只能是:xml, html,script,json,jsonp,text。 无法接受blob类型的response。 当后端返回给前端一个文件流的时候,前端ajax会将文件流转化成string 类型。 无法正确读取改文件流,导致文本内容乱码。

解决方案:

前端在实现文件下载功能时,请不要使用ajax请求。我们可以使用XMLHttpRequest来代替ajax, 请看下面的代码:

const xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
//定义responseType='blob', 是读取文件成功的关键,这样设置可以解决下载文件乱码的问题
xhr.responseType = "blob";    
xhr.onload = () => {
//'\ufeff' 这个变量是定义字符集为utf-8, 防止中文乱码的问题。
// {type: 'application/msword'} 根据文档类型来定义这个type。MIMA type
  const blob = new Blob(["\ufeff", xhr.response], {type: 'application/msword'});
  const blobUrl = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.style.display = 'none';
  a.href = blobUrl;
  a.target = '_blank';
  a.click();
  }              
};
             
xhr.send(null);

文件下载成功截图:

更多推荐

前端 js jQuery ajax实现文件流下载, 下载doc,xsl等文件内容乱码问题