阅读 843

js 导出json文件,读取json文件,拖拽预览图片

将数据导出为json文件

<div id="download">导出</div>

    <script>

        var download = document.getElementById('download');
        download.addEventListener("click", () => downLoadFiles({ name: 111 }, 'test.json'), false);
        /**
         * 
         * @param {any} data 要导出的数据
         * @param {string} fileName 导出的文件名
         */
        const downLoadFiles = (data, fileName) => {
            if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) {
                //兼容ie10
                var blob = new Blob([JSON.stringify(data)], {
                    type: "data:application/json;charset=utf-8"
                });
                navigator.msSaveOrOpenBlob(blob, fileName);
            } else {
                const a = document.createElement("a");
                a.style.visibility = "hidden";
                document.body.appendChild(a);
                var blobs = new Blob([JSON.stringify(data)], {
                    type: "data:application/json;charset=utf-8"
                });
                var objurl = URL.createObjectURL(blobs);
                a.href = objurl;
                // a.href = "data:application/json;charset=utf-8" + JSON.stringify(data, null, 2);  // 使用这种方式会导出文件失败net error,原因在于协议不同无法跨域
                a.download = fileName;
                a.click();
                document.body.removeChild(a);
            }
        };
    </script>
复制代码

读取本地json文件

<div id="read">读取</div>

    <script>
        /**
          * 利用input标签的type=file属性来读取文件,点击绑定preImport事件的元素会让用户从本地目录选取文件,input标签的multiple属性支持一次选取多个文件
          */
        var preImport = () => {
            console.log('duqu');
            const id = "files";
            const input = document.createElement("input");
            input.id = id;
            input.type = "file";
            document.body.appendChild(input);
            input.onchange = () => importFile(id);
            input.click();

        };

        var importFile = (inputId) => {
            var files = document.getElementById(inputId);
            var selectedFile = files.files[0];
            var name = selectedFile.name; // 文件名

            var reader = new FileReader(); //这里是核心!!!读取操作就是由它完成的。
            reader.readAsText(selectedFile); //读取文件的内容
            reader.onload = function () {
                console.log(JSON.parse(this.result)); //此时文件的内容存储到了result中。直接操作即可。
            };

        };
        var read = document.getElementById('read');
        read.addEventListener("click", preImport, false);
    </script>

复制代码

使用拖放操作来选择要读取的图片并预览

 <div id="drop_zone" style="width: 400px;height: 400px;border:1px solid #000">Drop files here</div>
    <div id="list" style="width: 200px;height: 200px;border:1px solid red"></div>

    <script>
        window.onload = function () {

            var dragZone = document.getElementById('drop_zone');
            dragZone.addEventListener("dragover", handleDragOver, false);
            dragZone.addEventListener("drop", handleFileSelect, false);

            function handleFileSelect(e) {
                e.stopPropagation();
                e.preventDefault();

                var files = e.dataTransfer.files; // file list

                var output = [];
                for (var f of files) {
                    var reader = new FileReader();
                    reader.readAsDataURL(f);
                    //读取文件的内容
                    reader.onload = function () {
                        var img = document.createElement("img");
                        img.src = this.result;//将图片base64字符串赋值给img的src
                        img.style = 'width: 100px;height:auto';
                        document.getElementById("list").appendChild(img);
                    };

                }

            }

            function handleDragOver(e) {
                e.stopPropagation();
                e.preventDefault();
            }

        }

    </script>

复制代码