文件流下载与预览

对接口返回的文件流进行下载与预览

function downloadFile(uuid) {
    
    
   return request.default({
    
    
     method: "get",
     url: baseUrl + uuid,
     responseType: "arraybuffer",	// 改为blob则不需要转换
   });
 },

// 下载文件预览
async function viewFile(uuid) {
    
    
  const file = await downloadFile(uuid);  // 下载接口,返回文件流
  const blob = new Blob([file]);
  const reader = new FileReader();
  reader.readAsDataURL(blob);		// 图片预览
  // reader.readAsText(blob, "utf-8");		// 文本文件预览
  reader.onload = () => {
    
    
    // 返回文件路径
    this.imgUrl = reader.result	
    // this.textData = reader.result	
  };
}

// 下载文件
function handleDownloadFile(uuid, fileName) {
    
    
  const file = await downloadFile(uuid);  // 下载接口,返回文件流
  const blob = new Blob([file]);
  
  const a = document.createElement("a");
  const objectUrl = URL.createObjectURL(blob);
  a.setAttribute("href", objectUrl);
  a.setAttribute("download", fileName);
  a.click();

  URL.revokeObjectURL(a.href); // 释放url
}

tips:
在预览文件上 FileReaderURL.createObjectURL 都可以使用。但是 URL.createObjectURL 生成的url放在img上,img节点删除后,url似乎会被释放,无法再次使用。

文档链接

URL.createObjectURL
FileReader

猜你喜欢

转载自blog.csdn.net/m0_49343686/article/details/126488439
今日推荐