js-文件读写和上传下载的简单例子01
现下,网络越来越快,浏览器的功能和性能越来越好,所以很多时候,已经不需要一些复杂的框架来实现不是非常复杂的功能。
我们只有在以下情况才会考虑使用框架或者现成的第三方组件:
1.功能复杂,自己写没有必要
2.有必要套套壳子,在必要的时候更换壳子内的功能
只不过我本人,更加喜欢自己动手,也更加喜欢原生的东西。
以下代码是通过多个网络来源组装而成的,此处不在一一列出出处。
例子中示例了三个基本功能:
1.浏览器读文件,并使用ajax上传文件
2.原生方式上传文件
3.浏览器写文件,借助了第三方的fileSaver.js
4.POST json参数并下载附件
例子一:ajax上传文件、原生方式上传文件、FileSaver.js保存文本
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Js实现文件上传功能</title> <link rel="stylesheet" href="/css/msgbox.css" /> <link rel="stylesheet" href="/plugin/jquery/jquery-confirm/dist/jquery-confirm.min.css"> <link rel="stylesheet" href="/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="/plugin/jquery/jquery-3.4.1.min.js"></script> <!-- 提示框的引入 --> <script type="text/javascript" src="/promptbox/js/msgbox.js"></script> <script type="text/javascript" src="/promptbox/init_hide.js"></script> <script src="/plugin/jquery/jquery-confirm/dist/jquery-confirm.min.js"></script> <!-- 前端保存工具引入 --> <script src="/plugin/common/FileSaver.js"></script> <!-- jquery 全局侦听重定向 --> <script src="/plugin/jquery/jquery.pub.js"></script> <script> function exportMeta() { let sTableId = $("#tableId").val(); $.ajax({ url: "/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: "/test/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: "/test/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>
例子二、原生发送json参数并下载附件
/** * 导出所有满足条件的内容为excel格式 */ function exportClick() { let _param = getParamValue(); var url = '/log/srv/export'; var xhr = new XMLHttpRequest(); xhr.open('POST', url, true); // 也可以使用POST方式,根据接口 xhr.setRequestHeader('content-type', 'application/json'); xhr.responseType = "blob"; // 返回类型blob // 定义请求完成的处理函数,请求前也可以增加加载框/禁用下载按钮逻辑 xhr.onload = function () { // 请求完成 if (this.status === 200) { var blob = this.response; var reader = new FileReader(); reader.readAsDataURL(blob); reader.onload = function (e) { // 转换完成,创建一个a标签用于下载 var a = document.createElement('a'); a.download = '服务日志.xlsx'; a.href = e.target.result; $("body").append(a); a.click(); $(a).remove(); //记得移除,否则多点击几次后,页面会累积太多标签 }; } }; // 发送ajax请求 xhr.send(JSON.stringify(_param)); }
注:后端是直接输出二进制流的
try { String outputFileName = fileName; if (userAgent.toUpperCase().indexOf("MSIE") > 0) { outputFileName = URLEncoder.encode(fileName, "UTF-8"); } else if (userAgent.toUpperCase().indexOf("IPHONE") > 0) { outputFileName = new String(fileName.getBytes(), "ISO-8859-1"); } else { outputFileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1"); } response.setContentType("application/octet-stream"); response.setHeader("Content-disposition", "attachment; filename=\"" + outputFileName + "\""); wb.write(response.getOutputStream()); response.getOutputStream().flush(); } catch (Exception e) { System.out.println(e.getMessage()); }