前端input<File>读取本地文本文件 | FileReader

主要用到了以下api
FileReader
<input type="file">

function addData(){
    let input = document.createElement('input');
    input.type = 'file';
    input.accept = ".jpg, .jpeg, .png, .geojson"
    input.onchange = e => {
        let file = e.target.files[0];
        let info = file.name.split('.');
        let name = info[0] ?? '暂无';
        let format = info?.at(-1);
        // 这里进行格式判断,不同格式不同处理方式
        if (".jpg, .jpeg, .png".includes(format)) {
            console.log(name, format);
            let imgBlob = URL.createObjectURL(file);
            addImageToMap(imgBlob, name);
        } else if ('.geojson'.includes(format)) {
            console.log(name, format);
            var reader = new FileReader();
            reader.onload = (e)=> {
                // 读取内容并转为json格式
                console.log(JSON.parse(e.target.result));
            };
            reader.readAsText(file);
        }

    }
    input.click();
}

演示

posted @ 2022-11-10 16:28  槑孒  阅读(134)  评论(0编辑  收藏  举报