zoukankan      html  css  js  c++  java
  • [html5+java]文件异步读取及上传核心代码

    html5+java 文件异步读取及上传关键代码段

    功能:

    1.多文件文件拖拽上传,file input 多文件选择

    2.html5 File Api 异步FormData,blob上传,图片显示

    3.java端接受

    核心代码:

    1.拖拽代码段:

     1 <div id="dropzone">
     2     <div>Drag & drop your file here...</div>
     3     <div id='showFile'></div>
     4     <div style='clear: both'></div>
     5 </div>
     6 
     7 <script>
     8     /*function for drag and drop*/
     9     window.onload = function() {
    10         var dropzone = document.getElementById("dropzone");
    11         dropzone.ondragover = dropzone.ondragenter = function(event) {
    12             event.preventDefault();
    13             event.stopPropagation();
    14         }
    15         dropzone.ondrop = function(event) {
    16             event.preventDefault();
    17             var filesArray = event.dataTransfer.files;
    18             for ( var i = 0; i < filesArray.length; i++) {
    19                 var fObj = new fileObj(filesArray[i], idTmp);
    20                 // to do tasks with dropData
    21             }
    22             event.stopPropagation();
    23         }
    24     }
    25 </script>
    View Code

    file input 多文件选择:

     1 <p>
     2 Upload File: <input id='uploadFile' type="file" name="file" multiple />
     3 </p>
     4 
     5 <script>
     6 $("#uploadFile").change(function(e) {
     7     event.preventDefault();
     8     var filesArray = e.target.files;
     9     for ( var i = 0; i < filesArray.length; i++) {
    10         var fObj = new fileObj(filesArray[i], idTmp);
    11         // to do tasks with dropData
    12         idTmp++;
    13     }
    14     event.stopPropagation();
    15 });
    16 </script>
    View Code

    2.html5 File Api 异步上传:

    1).使用FormData上传

     1 <!DOCTYPE html>
     2 <html>
     3 <head>
     4     <title>Upload Files using XMLHttpRequest - Minimal</title>
     5 
     6     <script type="text/javascript">
     7       function fileSelected() {
     8         var file = document.getElementById('fileToUpload').files[0];
     9         if (file) {
    10           var fileSize = 0;
    11           if (file.size > 1024 * 1024)
    12             fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
    13           else
    14             fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
    15 
    16           document.getElementById('fileName').innerHTML = 'Name: ' + file.name;
    17           document.getElementById('fileSize').innerHTML = 'Size: ' + fileSize;
    18           document.getElementById('fileType').innerHTML = 'Type: ' + file.type;
    19         }
    20       }
    21 
    22       function uploadFile() {
    23         var fd = new FormData();
    24         fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
    25         var xhr = new XMLHttpRequest();
    26         xhr.upload.addEventListener("progress", uploadProgress, false);
    27         xhr.addEventListener("load", uploadComplete, false);
    28         xhr.addEventListener("error", uploadFailed, false);
    29         xhr.addEventListener("abort", uploadCanceled, false);
    30         xhr.open("POST", "UploadMinimal.aspx");
    31         xhr.send(fd);
    32       }
    33 
    34       function uploadProgress(evt) {
    35         if (evt.lengthComputable) {
    36           var percentComplete = Math.round(evt.loaded * 100 / evt.total);
    37           document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
    38         }
    39         else {
    40           document.getElementById('progressNumber').innerHTML = 'unable to compute';
    41         }
    42       }
    43 
    44       function uploadComplete(evt) {
    45         /* This event is raised when the server send back a response */
    46         alert(evt.target.responseText);
    47       }
    48 
    49       function uploadFailed(evt) {
    50         alert("There was an error attempting to upload the file.");
    51       }
    52 
    53       function uploadCanceled(evt) {
    54         alert("The upload has been canceled by the user or the browser dropped the connection.");
    55       }
    56     </script>
    57 </head>
    58 <body>
    59 <form id="form1" enctype="multipart/form-data" method="post" action="upload.php">
    60 <div class="row">
    61       <label for="fileToUpload">Select a File to Upload</label>
    62 <input type="file" name="fileToUpload" id="fileToUpload" onchange="fileSelected();"/>
    63     </div>
    64 <div id="fileName"></div>
    65 <div id="fileSize"></div>
    66 <div id="fileType"></div>
    67 <div class="row">
    68 <input type="button" onclick="uploadFile()" value="Upload" />
    69     </div>
    70 <div id="progressNumber"></div>
    71 </form>
    72 
    73 </body>
    74 </html>
    View Code

    2).使用blob,readAsBinaryString上传

      1 <!DOCTYPE html>
      2 <html>
      3 <head>
      4 <meta charset="UTF-8">
      5 <title>HTML5 File Upload[By WangXinsheng]</title>
      6 <script src="../js/jquery-1.11.1.min.js"></script>
      7 </head>
      8 <style>
      9 #dropzone {
     10     margin-top: 10px;
     11     width: 500px;
     12     min-height: 300px;
     13     height: 100%;
     14     border: 1px dotted grey;
     15 }
     16 
     17 header {
     18     font-weight: bold;
     19 }
     20 
     21 .uploadFile {
     22     display: inline;
     23     float: left;
     24     width: 45%;
     25     border: 1px solid gray;
     26     margin: 5px;
     27     min-height: 20px;
     28     padding-bottom: 5px;
     29     padding-left: 5px;
     30 }
     31 
     32 .uploadFile p {
     33     margin: 2px;
     34 }
     35 
     36 .uploadFile progress {
     37     -webkit-appearance: none;
     38 }
     39 .uploadFile .ok{
     40     cursor:pointer;
     41 }
     42 
     43 .uploadFile ::-webkit-progress-inner-element {
     44     
     45 }
     46 
     47 .uploadFile ::-webkit-progress-bar {
     48     background: white;
     49     border: 1px solid gray;
     50 }
     51 
     52 .uploadFile ::-webkit-progress-value {
     53     background: green;
     54 }
     55 
     56 .uploadFile ::-moz-progress-bar {
     57     background: white
     58 }
     59 
     60 .uploadFile ::-ms-fill {
     61     background: green;
     62 }
     63 </style>
     64 <body>
     65     <header>HTML5 File Upload</header>
     66     <p>
     67         Upload File: <input id='uploadFile' type="file" name="file" multiple />
     68     </p>
     69 
     70     <div id="dropzone">
     71         <div>Drag & drop your file here...</div>
     72         <div id='showFile'></div>
     73         <div style='clear: both'></div>
     74     </div>
     75     <script>
     76         var oneFileDom = "<div class='uploadFile' id='uf_{%id%}'>"
     77         +"<p>{%name%}</p>"
     78         +"<progress width='100%'></progress>"
     79         +"<span class='ok' style='display:none;padding-left:10px;color:green;font-weight:bold__:bold;'>转换</span>"
     80         +"</div>";
     81         var idTmp = 0;
     82         /*all file obj list*/
     83         var fileObjLst = [];
     84         /*file object*/
     85         var fileObj = function(file, id) {
     86             this.fileName;
     87             this.file = file;
     88             this.uploadSize = 0;
     89             this.finishFlg = false;
     90             this.sliceStart = 0;
     91             this.maxPiece = 0;
     92             this.blockCount = 0;
     93             this.blockCur = 0;
     94             this.reader = null;
     95             this.dom;
     96             this.id = id;
     97             this.xhr;
     98         }
     99         fileObj.prototype.init = function() {
    100             var tmpPiece = Math.ceil(this.file.size * 0.5);
    101             this.maxPiece = tmpPiece > 1024 * 1024 * 0.2 ? 1024 * 1024 * 0.2
    102                     : (tmpPiece < 1024 * 1024 * 0.1 ? 1024 * 1024 *0.1: tmpPiece);
    103             this.blockCount = Math.ceil(this.file.size / this.maxPiece);
    104             this.sliceEnd = this.maxPiece;
    105             this.fileName = new Date().getTime();
    106             $("#showFile").prepend(
    107                     $(oneFileDom.replace('{%id%}', this.id).replace("{%name%}",
    108                             this.file.name)));
    109         }
    110         fileObj.prototype.send = function() {
    111             console.log(this.id);
    112             $("#uf_" + this.id).find("progress").attr("value", '0');
    113             $("#uf_" + this.id).find("progress").attr("max",
    114                     this.file.size + '');
    115 
    116             this.reader = new FileReader();
    117 
    118             this.Bind(this.reader, "loadend", this.onloadend, this);
    119             this.Bind(this.reader, "loadstart", this.onloadstart, this);
    120             this.Bind(this.reader, "progress", this.onprogress, this);
    121             this.Bind(this.reader, "load", this.onload, this);
    122 
    123             var blob, file = this.file;
    124             console.log(file);
    125             try {
    126                 blob = sliceBlob(file, this.sliceStart, this.sliceStart
    127                         + this.maxPiece + 1);
    128             } catch (e) {
    129                 console.log("error:" + e);
    130             }
    131             this.sliceStart = this.sliceStart + this.maxPiece + 1;
    132             this.reader.readAsBinaryString(blob);
    133         }
    134         fileObj.prototype.onload = function() {
    135             // 这个事件在读取成功结束后触发
    136             console.log("load complete");
    137         }
    138         fileObj.prototype.onloadstart = function() {
    139             // 这个事件在读取开始时触发
    140             console.log("onloadstart");
    141             //document.getElementById("bytesTotal").innerHTML = file.size;
    142         }
    143         fileObj.prototype.onprogress = function(p) {
    144             // 这个事件在读取进行中定时触发
    145             console.log("onprogress");
    146             //document.getElementById("bytesRead").textContent = p.loaded;
    147         }
    148         fileObj.prototype.onloadend = function() {
    149             // 这个事件在读取结束后,无论成功或者失败都会触发
    150             //console.log(this.id);
    151             if (this.reader.error) {
    152                 console.log(this.reader.error);
    153             } else {
    154                 var url1 = "/ExcelToWord/morning?over=0&fileName=["
    155                         + this.fileName + "]" + this.file.name, url2 = "/ExcelToWord/morning?over=1&fileName=["
    156                         + this.fileName + "]" + this.file.name, url = url1;
    157                 this.blockCur++;
    158 
    159                 this.uploadSize = ((this.sliceStart - 1) < this.file.size) ? (this.sliceStart - 1)
    160                         : this.file.size;
    161                 $("#uf_" + this.id).find("progress").attr("value",
    162                         this.uploadSize + '');
    163                 console.log(this.uploadSize, this.file.size);
    164                 if (this.blockCur > this.blockCount) {
    165                     //$("#uf_"+this.id).find(".ok").show();
    166                     console.log('over');
    167                     return;
    168                 } else if (this.blockCur == this.blockCount) {
    169                     // last piece
    170                     console.log('last');
    171                     url = url2;
    172                 }
    173                 console.log(this.blockCur, this.blockCount);
    174                 // 构造 XMLHttpRequest 对象,发送文件 Binary 数据
    175                 var me = this;
    176                 this.xhr = new XMLHttpRequest();
    177                 this.xhr.open("POST", url);
    178                 this.xhr.overrideMimeType("application/octet-stream");
    179                 this.xhr.sendAsBinary(this.reader.result);
    180                 this.Bind(this.xhr, "readystatechange",
    181                         this.onreadystatechange, this);
    182             }
    183         }
    184         fileObj.prototype.onreadystatechange = function() {
    185             var me = this;
    186             if (this.xhr.readyState == 4) {
    187                 if (this.xhr.status == 200) {
    188                     console.log("upload complete");
    189                     console.log("response: " + this.xhr.responseText);
    190                     console.log("hello" + me.id);
    191                     var json = eval("(" + this.xhr.responseText + ")");
    192                     console.log(json.over);
    193                     if (json.over == "1") {
    194                         $("#uf_" + this.id).find(".ok").attr("serverName",
    195                                 json.data);
    196                         $("#uf_" + this.id).find(".ok").show();
    197                         console.log('over');
    198                         return;
    199                     }
    200                     var blob, file = me.file;
    201                     try {
    202                         blob = sliceBlob(file, me.sliceStart, me.sliceStart
    203                                 + me.maxPiece + 1);
    204                     } catch (e) {
    205                         console.log("error:" + e);
    206                     }
    207                     me.sliceStart = me.sliceStart + me.maxPiece + 1;
    208                     me.reader.readAsBinaryString(blob);
    209                 }
    210             }
    211         }
    212         fileObj.prototype.Bind = function(control, eventName, callBack, scope) {
    213             if (!scope) {
    214                 scope = window;
    215             }
    216             $(control).bind(eventName, function() {
    217                 callBack.apply(scope, arguments);
    218             });
    219         }
    220         function sliceBlob(blob, start, end, type) {
    221 
    222             type = type || blob.type;
    223 
    224             if (blob.mozSlice) {
    225                 return blob.mozSlice(start, end, type);
    226             } else if (blob.webkitSlice) {
    227                 return blob.webkitSlice(start, end, type);
    228             } else if (blob.slice) {
    229                 return blob.slice(start, end, type);
    230             } else {
    231                 throw new Error("This doesn't work!");
    232             }
    233         }
    234         /*function for drag and drop*/
    235         window.onload = function() {
    236             var dropzone = document.getElementById("dropzone");
    237             dropzone.ondragover = dropzone.ondragenter = function(event) {
    238                 event.preventDefault();
    239                 event.stopPropagation();
    240             }
    241             dropzone.ondrop = function(event) {
    242                 event.preventDefault();
    243                 var filesArray = event.dataTransfer.files;
    244                 for ( var i = 0; i < filesArray.length; i++) {
    245                     var fObj = new fileObj(filesArray[i], idTmp);
    246                     fObj.init();
    247                     fObj.send(fObj);
    248                     fileObjLst.push(fObj);
    249                     idTmp++;
    250                 }
    251                 event.stopPropagation();
    252             }
    253             $("#uploadFile").change(function(e) {
    254                 event.preventDefault();
    255                 var filesArray = e.target.files;
    256                 for ( var i = 0; i < filesArray.length; i++) {
    257                     var fObj = new fileObj(filesArray[i], idTmp);
    258                     fObj.init();
    259                     fObj.send(fObj);
    260                     fileObjLst.push(fObj);
    261                     idTmp++;
    262                 }
    263                 event.stopPropagation();
    264             });
    265         }
    266 
    267         if (window.navigator.userAgent.toLowerCase().indexOf("chrome") > -1) {
    268             XMLHttpRequest.prototype.sendAsBinary = function(datastr) {
    269                 function byteValue(x) {
    270                     return x.charCodeAt(0) & 0xff;
    271                 }
    272                 var ords = Array.prototype.map.call(datastr, byteValue);
    273                 var ui8a = new Uint8Array(ords);
    274                 this.send(ui8a.buffer);
    275             }
    276         }
    277     </script>
    278 </body>
    279 </html>
    View Code

    3).Image 文件上传本地预览

    1 // 图片文件
    2 var reader = new FileReader();
    3 reader.readAsDataURL(imageFile);
    4 // reader读取完成的回调,设置src属性,显示图片.
    5 // 或者设置css的背景属性都可
    6 reader.onload = function(e) {
    7         document.getElementById('imageId').src = e.target.result;
    8 }
    View Code

    3.java端接受

     1     @RequestMapping("/url")
     2     @ResponseBody
     3     public Map<String, Object> handleRequest(HttpServletRequest request,
     4             HttpServletResponse response) throws Exception  {
     5         String fileName = request.getParameter("fileName");
     6         fileName = new String(fileName.getBytes("ISO-8859-1"),"UTF-8");
     7         String overFlg = request.getParameter("over"); // 0:go on;1:over
     8         System.out.println("get: " + fileName);
     9         byte[] buf = new byte[1024];
    10 
    11         File file = new File(ExcelTmpPath + /*"[" + UUID.randomUUID().toString()
    12                 + "]" +*/ fileName);
    13         InputStream is = null;
    14         BufferedOutputStream fileOut = new BufferedOutputStream(
    15                 new FileOutputStream(file, true));
    16         try {
    17 
    18             is = request.getInputStream();
    19 
    20             while (true) {
    21 
    22                 int bytesIn = is.read(buf, 0, 1024);
    23                 System.out.println(bytesIn);
    24                 if (bytesIn == -1) {
    25                     break;
    26                 } else {
    27                     fileOut.write(buf, 0, bytesIn);
    28                 }
    29             }
    30 
    31             fileOut.flush();
    32             fileOut.close();
    33             System.out.println(file.getAbsolutePath());
    34         } catch (IOException e) {
    35             System.out.println("error  info");
    36         }
    37         Map<String, Object> map = new HashMap<String, Object>();
    38         map.put("over", overFlg);
    39         map.put("data", fileName);
    40         return map;
    41     }
    View Code
  • 相关阅读:
    各种小知识
    基础技能
    st表
    有理数取余
    FFT加速高精度乘法
    unique
    离散化
    线段树复杂度分析
    楼房重建
    电脑装系统常用方法
  • 原文地址:https://www.cnblogs.com/wangxinsheng/p/4321284.html
Copyright © 2011-2022 走看看