js-文件读写和上传下载的简单例子01

现下,网络越来越快,浏览器的功能和性能越来越好,所以很多时候,已经不需要一些复杂的框架来实现不是非常复杂的功能。

我们只有在以下情况才会考虑使用框架或者现成的第三方组件:

1.功能复杂,自己写没有必要

2.有必要套套壳子,在必要的时候更换壳子内的功能

只不过我本人,更加喜欢自己动手,也更加喜欢原生的东西。

以下代码是通过多个来源组装而成的,例子中示例了三个基本功能:

1.浏览器读文件,并使用ajax上传文件

2.原生方式上传文件

3.浏览器写文件,借助了第三方的fileSaver.js

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Js实现文件上传功能</title>
    <link rel="stylesheet" href="/rap/promptbox/css/msgbox.css" />
    <link rel="stylesheet" href="/rap/plugin/jquery/jquery-confirm/dist/jquery-confirm.min.css">
    <link rel="stylesheet" href="/rap/css/public.css">
    <style>
        .a-upload {
            position: relative;
            display: inline-block;
            background: #D0EEFF;
            border: 1px solid #99D3F5;
            border-radius: 4px;
            padding: 4px 12px;
            overflow: hidden;
            color: #1E88C7;
            text-decoration: none;
            text-indent: 0;
            line-height: 20px;
        }

        .a-upload input {
            position: absolute;
            font-size: 100px;
            right: 0;
            top: 0;
            opacity: 0;
        }

        .a-upload:hover {
            background: #AADFFD;
            border-color: #78C3F3;
            color: #004974;
            text-decoration: none;
        }
    </style>
</head>

<body>
    <div style="display: none;">
        <h3>原生上传</h3>
        <form method="post" enctype="multipart/form-data" id="upload">
            <a href="javascript:;" id="pic" class="a-upload">
                <input type="file" name="file">点击这里上传文件
            </a>
            <input type="button" value="提交" onclick="uploadPic()">
            <span class="showUrl"></span>
            <img src="" alt="" class="showPic">
        </form>
    </div>
    

    <h3>本地读取文件</h3>
    <hr>
    <legend>
        <div>
            <input type="file" name="metaFile" id="metaFile">
            <input type="button" value="上传" onclick="uploadMeta()">
            <div>
                <div class="input-condition">
                    <label>是否覆盖现有表单:</label>
                    <input type="checkbox" id="overwriteExists" onchange="showNewSection()">
                </div>

                <div class="input-condition none-overwrite">
                    <label>新的表单存储名称:</label>
                    <input type="text" id="newDbname">
                </div>

                <div class="input-condition none-overwrite">
                    <label>新的表单显示名称:</label>
                    <input type="text" id="newShowName">
                </div>
            </div>
        </div>
    </legend>
    <h3>保存到本地</h3>
    <div>
        <label>tableId:</label><input type="text" id="tableId">
        <input type="button" onclick="exportMeta()" value="保存到本地">
    </div>
</body>
<script src="/rap/plugin/jquery/jquery-3.4.1.min.js"></script>
<!-- 提示框的引入 -->
<script type="text/javascript" src="/rap/promptbox/js/msgbox.js"></script>
<script type="text/javascript" src="/rap/promptbox/init_hide.js"></script>
<script src="/rap/plugin/jquery/jquery-confirm/dist/jquery-confirm.min.js"></script>
<!-- 前端保存工具引入 -->
<script src="/rap/plugin/common/FileSaver.js"></script>
<!-- jquery 全局侦听重定向 -->
<script src="/rap/plugin/jquery/jquery.pub.js"></script>

<script>


    function exportMeta() {
        let sTableId = $("#tableId").val();
        $.ajax({
            url: "/rap/custom/tool/getTableMeta",
            type: 'post',
            data: {
                "tableId": sTableId
            },
            success: function (res) {
                if (res.flag==1){
                    var blob = new Blob([res.data.tableMetaJson], { type: "text/plain;charset=utf-8" });
                    saveAs(blob, "tableMeta.json");
                }
                else{
                    clickAutoHide(2,res.msg, null);
                }
               
            },
            error: function (err) {
                alert('网络失败,请稍后再试', err)
            }
        })
    }

    function showNewSection() {
        if (document.getElementById("overwriteExists").checked) {
            $(".none-overwrite").css("display", "none");
        }
        else {
            $(".none-overwrite").css("display", "block");
        }
    }
    function uploadMeta() {
        //获取读取我文件的File对象
        let selectedFile = document.getElementById('metaFile').files[0];
        let name = selectedFile.name; //读取选中文件的文件名
        let size = selectedFile.size; //读取选中文件的大小
        console.log("文件名:" + name + "大小:" + size);
        let reader = new FileReader(); //这是核心,读取操作就是由它完成.
        reader.readAsText(selectedFile); //读取文件的内容,也可以读取文件的URL

        reader.onload = function (e) {
            //当读取完成后回调这个函数,然后此时文件的内容存储到了result中,直接操作即可
            var metaString = this.result;
            $.ajax({
                url: "/rap/custom/tool/importTableMeta",
                type: 'post',
                data: {
                    "metaString": metaString,
                    "overwriteExists": false,//不覆盖现有的
                    "newDbname": "testload001",
                    "newShowName": "导入测试001"
                },
                success: function (res) {
                    alert(res.msg);
                },
                error: function (err) {
                    alert('网络失败,请稍后再试', err)
                }
            })
        }
    }
    function uploadPic() {
        let form = document.getElementById('upload')
        let formData = new FormData(form);
        $.ajax({
            url: "/rap/attach/upload",
            type: 'post',
            data: formData,
            processData: false,
            success: function (res) {
                if (res) {
                    alert('上传成功')
                }
                $('#pic').val('');
                $(".showUrl").html(res);
                $(".showPic").attr("src", res);
            },
            error: function (err) {
                alert('网络失败,请稍后再试', err)
            }
        })
    }
</script>

</html>
原文地址:https://www.cnblogs.com/lzfhope/p/15422434.html