目录

前端乱码文件流处理

目录

前端乱码文件流处理

在处理后端返回文件时,经常会遇到乱码情况 https://i-blog.csdnimg.cn/blog_migrate/1f1d408f3be34ad3a88940b4ed393fd6.png

通过文件后缀名判断媒体格式

function getMimeTypeBySuffix(suffix) {
  let mimeType = '';
  switch (suffix.toLowerCase()) {
    case 'html': mimeType = 'text/html';
      break;
    case 'txt': mimeType = 'text/plain';
      break;
    case 'gif': mimeType = 'image/gif';
      break;
    case 'jpeg': mimeType = 'image/jpeg';
      break;
    case 'jpg': mimeType = 'image/jpeg';
      break;
    case 'png': mimeType = 'image/png';
      break;
    case 'mp4': mimeType = 'video/mp4';
      break;
    case 'mpg': mimeType = 'video/mpeg';
      break;
    case 'mpeg': mimeType = 'video/mpeg';
      break;
    case 'avi': mimeType = 'video/x-msvideo';
      break;
    case 'gz': mimeType = 'application/x-gzip';
      break;
    case 'tar': mimeType = 'application/x-tar';
      break;
    case 'doc': mimeType = 'application/msword';
      break;
    case 'docx': mimeType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
      break;
    case 'xls': mimeType = 'application/vnd.ms-excel';
      break;
    case 'xlsx': mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
      break;
    case 'ppt': mimeType = 'application/vnd.ms-powerpoint';
      break;
    case 'pptx': mimeType = 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
      break;
    case 'gzip': mimeType = 'application/x-gzip';
      break;
    case 'zip': mimeType = 'application/zip';
      break;
    case '7zip': mimeType = 'application/zip';
      break;
    case 'rar': mimeType = 'application/rar';
      break;
    case 'pdf': mimeType = 'application/pdf';
      break;
  }
  return mimeType;
}

请求代码

function getRes() {
  return axios({
    url: `请求地址`,
    method: 'get',
    responseType: "arraybuffer" // "arraybuffer" 或者 "blod",告诉服务器以二进制方式返回
  });
}

核心转换代码

getBlodUrl(res,fileName){ //res:后端返回的乱码,fileName 文件名
    //获取当前文件媒体格式
    let currentMimeType = getMimeTypeBySuffix(
         fileName.split(".").pop().toLowerCase()
    );
    let blob = new Blob([res.data], {
        type: currentMimeType,
    });
    return window.URL.createObjectURL(blob)
}

          

如果是图片可以直接放在img的src中

如果是文件,可以放入a标签的href属性中下载