导入、导出、下载一般通用写法(使用a标签下载时有的浏览器会直接打开页面,只需将图片的响应头Content-Disposition改为attachment即可)

// 导出通用写法
handleExport = () => {
    const filename = '二维码.png';
    let aEle = document.getElementById('aElement');
    if (!aEle) {
        try {
            aEle = document.createElement('<a  id="aElement">');
        } catch (e) {
            aEle = document.createElement('a');
        }
    }
    document.body.appendChild(aEle);
    aEle.style.display = 'none';
    aEle.href = qrCodeUrl;
    aEle.download = filename;
    aEle.click();
    document.body.removeChild(aEle);

    // 下面这个也可以
    const a = document.createElement('a');
    const href = `${url}`;
    a.href = href;
    a.click();
}


// 导入通用写法
handleImport = () => {
    const formData = new FormData();
    formData.append('file', this.File);

    fetch(url, {
        method: 'POST',
        body: formData
    })
    .then(res => res.json())
    .catch(err => console.error('Error', err))
    .then(res => {
        // 接口返回
    })
}

handleChangeFile = file => {
    const Files = file.target.files['0'];
    const fileSize = File.size;
    if (fileSize > 1024 * 1024 * 2) {
        return notice.setLastError({effect: 1, tip: '文件大小需不超过2MB'});
    }

    this.File = Files;
    const name = this.File ? this.File.name : '';
}    

handleUpload = () => {
    document.querySelector('#addUpload').click();
}

<Button onClick={this.handleUpload}>上传文件</Button>
<input
    style={{display: 'none'}}
    id="addUpload"
    type="file"
    name="addUpload"
    onChange={this.handleChangeFile}
 />






不使用a标签进行下载:

// 使用地址下载(urls为地址,get请求方式才能使用)
const downloadFile = (fileUrl, fileName) => {
        console.log(fileUrl, fileName);
        const xhr = new XMLHttpRequest();
        xhr.open('GET', fileUrl, true);
        xhr.responseType = 'blob';
        xhr.onload = function () {
            if (xhr.status === 200) {
                const blob = xhr.response;
                const link = document.createElement('a');
                link.href = window.URL.createObjectURL(blob);
                link.download = fileName;
                link.click();
            }
        };
        xhr.send();
};

// 使用二进制流下载(注意,这里data是二进制流转arrayBuffer了,接口返回的数据是二进制流,但必须转arrayBuffer, arrayBuffer在调用接口是就要传responseType: 'arrayBuffer')

downloadxlsx = data => {
        // data 是二进制流转arrayBuffer后的数据
        const time = this.formatDate(new Date(), 2);
        const nowDay = time.substring(0, 4) + time.substring(5, 7) + time.substring(8, 10);

        const url = window.URL.createObjectURL(new Blob([data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}));
       
        console.log(data, 'datadatadatadata');
       
        const link = document.createElement('a');
        //
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', `客户拨打数据${nowDay}.xlsx`);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    };

    formatDate = (date, type) => {
        date = typeof date === 'number' ? String(date) : date; // 时间戳如果是number类型转化成string类型
        // 匹配日期时间
        const matchDateTime = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/g;
        // 匹配日期
        const matchDate = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/g;
        // 匹配时间戳
        const matchTimeStamp = /[0-9]{13}|[0-9]{10}/g;
        if (typeof date !== 'object') {
            if (date.match(matchDate)) {
                //
                date = new Date(Date.parse(date.replace(/-/g, '/')));
            } else if (date.match(matchDateTime)) {
                //
                date = date.replace(/-/g, '/');
                date = new Date(date);
            } else if (date.match(matchTimeStamp)) {
                //
                date = new Date(Number(date));
            }
        }
        let result = null;
        // eslint-disable-next-line default-case
        switch (type) {
            case 1:
                result = formatdate(date, 1);
                break;
            case 2:
                result = formatdate(date, 2);
                break;
            case 3:
                result = formatweek(date);
                break;
            case 4:
                result = formattimestamp(date);
                break;
        }
        // 格式化日期/日期时间:yyyy-MM-dd/yyyy-MM-dd HH:mm:ss
        function formatdate(date, type) {
            const year = date.getFullYear();
            const month = addzero(date.getMonth() + 1);
            const weekday = addzero(date.getDate());
            const hour = addzero(date.getHours());
            const minute = addzero(date.getMinutes());
            const second = addzero(date.getSeconds());
            function addzero(value) {
                if (value < 10) {
                    value = `0${value}`;
                }
                return value;
            }
            if (type == 1) {
                return `${year}-${month}-${weekday}`;
            }
            return `${year}-${month}-${weekday} ${hour}:${minute}:${second}`;
        }
        // 格式化周几
        function formatweek(date) {
            let week;
            if (date.getDay() == 0) week = '星期日';
            if (date.getDay() == 1) week = '星期一';
            if (date.getDay() == 2) week = '星期二';
            if (date.getDay() == 3) week = '星期三';
            if (date.getDay() == 4) week = '星期四';
            if (date.getDay() == 5) week = '星期五';
            if (date.getDay() == 6) week = '星期六';
            return week;
        }
        // 格式化时间戳
        function formattimestamp(date) {
            const timestamp = date.getTime();
            return timestamp;
        }
        return result;
};

特殊的下载:阿里云(腾讯云)的地址,使用a标签download无法下载

// 特殊的下载:阿里云的地址,使用a标签download无法下载. 使用方法:downImg(url, fileName)
export.downImg = (src, fileName) => {
    const image = new Image();
    image.src = `${src}?v=${Math.random()}`; // 处理缓存
    image.crossOrigin = '*'; // 支持跨域图片
    image.onload = function () {
        const base64 = drawBase64Image(image);
        downFile(base64, fileName);
    };
}

function drawBase64Image(img) {
    const canvas = document.createElement('canvas');
    canvas.width = img.width;
    canvas.height = img.height;
    const ctx = canvas.getContext('2d');
    ctx.drawImage(img, 0, 0, img.width, img.height);
    const dataURL = canvas.toDataURL('image/png');
    return dataURL;
}
function downFile(url, name) {
    let filename = '海报.jpg';
    if (name) {
        filename = name;
    }
    const tmpa = document.createElement('a');
    tmpa.download = filename;
    tmpa.href = url; // 绑定a标签
    tmpa.target = url; // 绑定a标签
    tmpa.click(); // 模拟点击实现下载
}

根据图片地址使用二进制流下载

// 根据图片地址使用二进制流下载

fetch('https://example.com/image.jpg', {
  // 加这个是为了处理跨域
  method: 'GET',
  mode: 'cors',
  headers: {
    'Content-Type': 'image/jpeg'
  }
})
.then(response => response.blob())
.then(blob => {
  // 处理获取到的二进制数据
  console.log(blob);
});


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值