精华内容
下载资源
问答
  • html5+java文件异步读取及上传关键代码段 功能: 1.多文件文件拖拽上传,file input 多文件选择 2.html5 File Api 异步FormData,blob上传,图片显示 3.java端接受 核心代码: 1.拖拽代码段: 1 <...

    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

     

    转载于:https://www.cnblogs.com/wangxinsheng/p/4321284.html

    展开全文
  • 文件异步读取 java

    千次阅读 2011-08-09 21:14:00
    读 写 耗用时间(秒) RandomAccessFile RandomAccessFile 95.848 BufferedInputStream + DataInputStream BufferedOutputStream + DataOutputS
    耗用时间(秒)
    RandomAccessFile RandomAccessFile 95.848
    BufferedInputStream + DataInputStream BufferedOutputStream + DataOutputStream 2.935
    BufferedRandomAccessFile BufferedOutputStream + DataOutputStream 2.813
    BufferedRandomAccessFile BufferedRandomAccessFile 2.453
    BufferedRandomAccessFile 优 BufferedRandomAccessFile优 2.197
    BufferedRandomAccessFile 完 BufferedRandomAccessFile完 0.401
    MappedByteBuffer+ RandomAccessFile MappedByteBuffer+ RandomAccessFile 1.209


    做了一个视频断点续传的功能,开始使用的 RamdomAccessFile 实现的发现速度太慢了。后来换成 MappedByteBuffer + RandomAccessFile实现


    实例如下:

    RandomAccessFile raf = new RandomAccessFile(newFile, "rw");
                            long fileLength = Long.valueOf(newFile.length()).longValue();
    //                        raf.seek(start_point==null?fileLength:Long.parseLong(start_point));
    //                        raf.write(buffer);
                            FileChannel fc = raf.getChannel();
                            MappedByteBuffer out = fc.map(FileChannel.MapMode.READ_WRITE, 0, fileLength + length);
                            out.position(start_point == null ? (int) fileLength : Integer.parseInt(start_point));
                            out.put(buffer);
                            out.force();
                            fc.close();
                            is.close();

    展开全文
  • // 异步读取文件,这个./a.txt是一个文件,这里测试用来测试异步读取文件的。 fs.readFile('./a.txt', 'utf-8', (err, data) => { console.log(data);//必须使用回调函数来接收 }); // 同步读取文件,可...
    是一个js文件
    const fs = require('fs');
    
    console.log(111);
    
    // 异步读取文件,这个./a.txt是一个文件,这里测试用来测试异步读取文件的。
    fs.readFile('./a.txt', 'utf-8', (err, data) => {
        console.log(data);//必须使用回调函数来接收
    });
    
    // 同步读取文件,可以使用变量来接收
    // let data = fs.readFileSync('./a.txt', 'utf-8');//这个加上Sync就是同步了
    // console.log(data);
    
    console.log(222);
    
    // 这是异步请求过来的
    // 111
    // 222
    // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
    
    //这是同步请求过来的
    //111
    //aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
    //222
    
    展开全文
  • 异步读取文件       异步文件写入   异步事件   异步MySQL &lt;?php /** * Created by PhpStorm. * User: Ty_Ro * Date: 2018/11/18 * Time: 17:21 */ class Mysql{ public $...

    异步读取文件

     

     

     

    异步文件写入

     

    异步事件

     

    异步MySQL

    <?php
    /**
     * Created by PhpStorm.
     * User: Ty_Ro
     * Date: 2018/11/18
     * Time: 17:21
     */
    class Mysql{
        public $mysql = '';
        public $config = '';
        public function __construct()
        {
            $this->mysql = new swoole_mysql();
            $this->config = array(
                'host' => '127.0.0.1',
                'port' => 3306,
                'user' => 'root',
                'password' => 'root',
                'database' => 'swoole',
                'charset' => 'utf8', //指定字符集
            );
        }
    
        public function add(){
    
        }
    
        public function del(){
    
        }
    
        public function update(){
    
        }
    
        /**
         *  mysql 执行逻辑
         * @param $id
         * @param $username
         * @return bool
         */
        public function execute($id,$username){
            $this->mysql->connect($this->config,function ($mysql,$result){
                if($result===false){
                    var_dump($mysql->connect_errno);
                }
                var_dump('连接结果:'.$result);
            $sql = 'select * from test where id = 1 ';
            $this->mysql->query($sql,function ($mysql,$res){
                //$res   当为select时返回结果集,当为add,del,update时返回bool
                if($res===true){
                    //todo
                }elseif($res===false){
                    //todo
                }else{
                    var_dump($res);
                }
                $mysql->close();
            });
            });
                return true;
         }
    }
    
    $dbsource = new Mysql();
    $data = $dbsource->execute(1,'tang');
    var_dump($data).PHP_EOL;
    echo 'start'.PHP_EOL;
    
    
    // 详情页 -》mysql(阅读数) -》msyql 文章 +1 -》页面数据呈现出来
    

     

     

    展开全文
  • 异步操作可以使我们的程序获得更优的性能,特别是对大文件进行处理时,这一点相信大家都知道。这里我写了一个示例。希望能给大家一个帮助。using System.IO;using System.Threading;public class Form2 : System....
  • C#异步读取文件

    2016-07-25 19:32:00
    C#异步读取文件 eg:首先解释一下什么是异步,异步是主线程可以异步方法调用后不用等到其运行结束后再进行后续工作。那么主线程怎么知道异步操作结束呢:回调函数。异步不能直接提高效率,异步不是并行编程。异步与...
  • fileReade实现文件读取进度条 fileReade的与file.s实现文件切片读取 一、fileReader的方法与事件 1.方法 FileReader.abort():终止读取操作。返回时,readyState属性为DONE。 FileReader.readAsArrayBuffer...
  • Swoole IO异步读取文件与写入文件 持续更新简单IO异步读取文件 实现简单IO异步写入文件 实现 简单IO异步读取文件 实现 read.php &lt;?php /** * Created by PhpStorm. * User: dom * Date: 19-2-21 * Time: ...
  • 这篇文章我们学习如何用异步编程来读取文件。 使用System.IO.Stream类的异步调用方法,对文件out.txt进行异步读操作。 运行结果: 源代码: using System; using System.Collections.Generic; using System....
  • 1.异步读取地址下信息 public void T_Invoke() { var request = WebRequest.Create("http://www.sina.com.cn"); //io yibu request.BeginGetRequestStream(AsyncCall...
  • swoole异步读取文件、写入文件

    千次阅读 2018-10-25 10:16:20
    异步读取文件:swoole_async_readfile() /**读取文件**/ //sleep(3); $res = swoole_async_readfile(__DIR__.&quot;/test.txt&quot;,function($filename,$fileContent){ echo &quot;filename:.$...
  • // 按顺序来读取a、b、c三个文件的内容 ...// 封装一个函数,实现异步读取文件 let read = (path) => { return new Promise((resolve, reject) => { fs.readFile(path, 'utf-8', (err, data) => { ...
  • 主要介绍了PHP Swoole异步读取、写入文件操作,结合实例形式详细分析了php使用Swoole扩展异步操作文件读写的相关实现技巧,需要的朋友可以参考下
  • 异步读取文件实例

    2014-03-20 10:48:00
    通过异步的方式,读取sdcard中的文件,并显示读取进度,最后将读取文件显示在指定的位置 2、代码 1 package com.example.myfile; 2 3 import java.io.BufferedReader; 4 import java.io.File; 5 ...
  • 引入fs模块,同步读取函数readFileSync,异步读取函数readFile。  一般情况下NodeJS的每一个API都是异步的,作为一个单独的线程,它使用 异步函数 调用来 维护并发 。Node使用观察者模式。Node线程保持一个事件...
  • Swoole异步读取、写入文件

    千次阅读 2018-12-04 18:29:12
    异步读取文件:swoole_async_readfile 异步写入文件:swoole_async_writefile 【示例】 读取文件 readfile.php: &lt;?php $res = swoole_async_readfile(__DIR__."/1.txt", function($filename...
  • //引入他的模块之后调用读取文件的方法 fs.readFile('file.txt','utf-8',function(err,data){//回调函数有两个参数,一个是err表示错误信息,一个是读取文件的内容 if(err){ console.log(err); }else{ console...
  • gevent 异步读取文件

    2019-02-24 14:59:15
    gevent.monkey.patch_all() 并不会patch io....用gevent.fileobject.FileObjectThread 来包装 open 返回的文件对象;   import gevent import gevent.monkey; gevent.monkey.patch_all() from gevent.fileobject ...
  • node是可以异步读取文件,但是如果一下子异步读取的数量过大,则会抛出20错误 以下列出3种读取方式:同步,异步转同步,数量约束的异步 var t1, t2; t1 = +new Date; fileList.forEach(function(n, i) { var ...
  • Node.js-异步读取

    2020-04-13 13:00:12
    读取后缀名文件 异步读取 使用es6 异步编程处理 fs.readFile('ExtName/name.json', (err, jsondata) => { if (err) { throw err; } console.log(jsondata); }); let ext = JSON.parse(fs.readFileSync('ExtN....
  • Promise 异步读取文件 1.assets文件夹下创建txt ##2、 Promise封装文件读取 const fs = require('fs'); ​ //fs 封装成一个promise const readFile = function(fileName){ return new Promise((resolve,...
  • node同步异步读取文件

    2020-08-15 18:17:44
    //异步读取文件 response.end('ok'); console.log('主程序执行完毕'); } }).listen(8001); readfile.js的代码: var fs=require('fs'); module.exports={ readfileSync:function(path){//同步读取 var data=fs....
  • 异步读取文件的原理

    2018-11-21 15:12:56
    open函数内部不断判断是否读取就绪,就绪后调用回调函数。 &lt;script&gt; file=[] a={} a.txt='wait for long' a.js='i am js file' function sleep(delay) { var start = (new Date()).getTime(); ...
  • 一边读取文件内容一边做其它事情,异步请求 output.txt 你真棒 var fs=require('fs') console.log('程序开始运行'); fs.readFile('input.txt',function(err,data){ if(err){ return console.log(err); } co...
  • 本来是要学习AsyncTask的,当看到耗时操作时就考虑到了读取文件操作,然后自己试着读取raw文件夹下面的文件。 有两种方式读取,一种是按行读取,一种是按大小读取; 主要代码如下: 一:按行读取 关键代码: class...
  • 这个是异步读取文件的改进版。功能上更简洁一些,不过对同时访问同一个文件的互斥操作还没做好。 其改进主要是以下几点: 一:FileStream.Read的调用改为BeginRead, 二:报告进度的方法挪到BeginRead的回调方法...
  • 异步读取文件的改进

    千次阅读 2007-06-01 18:37:00
    这个是异步读取文件的改进版。功能上更简洁一些,不过对同时访问同一个文件的互斥操作还没做好。 其改进主要是以下几点:一:FileStream.Read的调用改为BeginRead,二:报告进度的方法挪到BeginRead的回调方法之中...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 2,950
精华内容 1,180
关键字:

文件异步读取