浏览器下载上传文件

2019-07-18  本文已影响0人  深度_1175

https://www.zhangxinxu.com/wordpress/2017/07/js-text-string-download-as-html-json-file/

var funDownload = function (domImg, filename) {
    // 创建隐藏的可下载链接
    var eleLink = document.createElement('a');
    eleLink.download = filename;
    eleLink.style.display = 'none';
    // 图片转base64地址
    var canvas = document.createElement('canvas');
    var context = canvas.getContext('2d');
    var width = domImg.naturalWidth;
    var height = domImg.naturalHeight;
    context.drawImage(domImg, 0, 0);
    // 如果是PNG图片,则canvas.toDataURL('image/png')
    eleLink.href = canvas.toDataURL('image/jpeg');
    // 触发点击
    document.body.appendChild(eleLink);
    eleLink.click();
    // 然后移除
    document.body.removeChild(eleLink);
};
<script>
    // 上传csv格式的文件
    function uploadfile() {
        let reads = new FileReader();
        file = document.getElementById('file').files[0];
        reads.readAsText(file, 'utf-8');
        console.log(reads);
        reads.onload = function (e) {
            console.log(e)
            // document.getElementById('result').innerText = this.result
            document.getElementById('result').innerText = e.target.result
        };
        reads.onloadstart = function(e) {
            console.log('onloadstart ---> ', e)
        }
        reads.onloadend = function(e) {
            console.log('onloadend ---> ', e)
        }
        reads.onprogress = function(e) {
            console.log('onprogress ---> ', e)
        }
    }

    // 上传image
    function uploadfile2() {
        let reads = new FileReader();
        file = document.getElementById('file2').files[0];
        reads.readAsDataURL(file);
        console.log(reads);
        reads.onload = function (e) {
            document.getElementById('img').src = this.result;
        };
    }
</script>
上一篇下一篇

猜你喜欢

热点阅读