前端下载文件

126 阅读1分钟

Blob对象方式

import axios from "axios"; 
// 资源路径 const path = "https://sf1-hscdn-tos.pstatp.com/obj/media-fe/xgplayer_doc_video/mp4/xgplayer-demo-360p.mp4" 
//发送请求,设置返回对象为Blob 
const res = await axios.get(path, { responseType: "blob" }); //将返回值通过URL.createObjectURL转成blob:http://xxx的地址 
const url = window.URL.createObjectURL(res.data); // 利用a标签进资源下载 
const link = document.createElement('a'); 
link.style.display = 'none'; 
link.href = url; 
link.download = '文件名'; 
document.body.appendChild(link); 
link.click(); 
document.body.removeChild(link);

base64方式

import axios from "axios"; 
// 资源路径 const path = "https://sf1-hscdn-tos.pstatp.com/obj/media-fe/xgplayer_doc_video/mp4/xgplayer-demo-360p.mp4" 
//发送请求,设置返回对象为Blob 
const res = await axios.get(fileUrl, { responseType: "blob" }); 
const reader = new FileReader(); // 传入被读取的blob对象 
reader.readAsDataURL(res.data); // 读取完成的回调事件 
reader.onload = () => { 
    // 生成的base64编码 
    const url = reader.result; 
    // 利用a标签进资源下载 
    const link = document.createElement('a'); 
    link.style.display = 'none';
    link.href = url; 
    link.download = '文件名'; 
    document.body.appendChild(link); 
    link.click(); 
    document.body.removeChild(link); 
};

canvas方式

download(link, picName) {
    const img = new Image();
    img.src = link
    // 前端对图片的跨域处理
    img.setAttribute("crossOrigin", "Anonymous");
    
    // 读取完成的回调事件
    img.onload = function () {
        const canvas = document.createElement("canvas");
        const context = canvas.getContext("2d");
        canvas.width = img.width;
        canvas.height = img.height;
        context.drawImage(img, 0, 0, img.width, img.height);
        // 生成的base64编码
        const url = canvas.toDataURL("images/png");
      
        // 利用a标签进资源下载
        const link = document.createElement('a');
        link.style.display = 'none'; 
        link.href = url;
        link.download = '文件名';
        document.body.appendChild(link); 
        link.click(); 
        document.body.removeChild(link);
    };
}