JavaScript完成写入文件到当地的主意,JavaScript使用享元方式完毕文件上传优化操作示例

正文实例讲述了JavaScript使用享元形式达成文件上传优化操作。分享给大家供大家参谋,具体如下:

当月做项目遭遇1个急需是上传文件,大致需求完毕的样式是那样子的,见下图:

本文实例讲述了JavaScript完结写入文件到本地的不二等秘书诀。分享给大家供大家参谋,具体如下:

一、享元格局是一种用于品质优化的方式,首要优化措施为,若系统中因为创建了大气看似的靶子而招致内部存款和储蓄器占用过高,则足以设想动用享元格局达成。

图片 1

干活中有的时候须求经过 JavaScript 保存文件到本地,我们都精晓 JavaScript
基于安全的设想,是不允许直接操作当和姑件的。

二、实例证实:

急需同一时候上传八个文件。并且规定文件格式和文件大小。因为前者框架使用angular,且不想因为八个上传效率又引进八个jquery,所以在互连网搜索基于angular的上传控件,因为angular还算比较新,貌似都未曾太成熟的插件,网络的学科也基本上是复制粘贴,总来说之没起倒多大的意义…可是百2秦关终属楚,最终如故让本身赶过了那个功效强大的插件,让笔者有种相见恨晚的认为啊,依赖官方文书档案和师兄的救助,终于搞明白了骨干的应用方法。好东西要享用,所以以往跟大家大快朵颐一下他的采取格局,借使大家刚刚需求使用,希望能帮到我们。

IE 能够由此 VB 插件的法子打开,而 Chrome 和 firefox 都不帮忙 JavaScript
向当地写入文件,所以 VB 插件的点子存在包容性难题。

若是在浏览器中上传文书,若使用正规写法,
每上传一个文书,就能够成立一个实例对象;假诺上传三千个公文,那就有两千个对象,浏览器很大概出现假死状态。这种景观下,大家思虑适应享元形式。

上传开关的体制 先是作者想先说一下上传文件的开关样式,为何呢?我们都知晓上传会用到这一个标签。<input
type=”file”/>,那行代码的暗许样式真的有些倒霉看,见下图:

那有未有合乎的章程吧?答案是必然的,我们能够通过 FileSaver.js
这几个小插件完结我们的要求。下边看1段具体的代码吧:

三、实例:

图片 2

/**
 * 下载文件
 */
var downloadTextFile = function(mobileCode) {
  if(isEmpty(mobileCode)) {
    mobileCode = '';
  }
  var file = new File([mobileCode], "手机号.txt", { type: "text/plain;charset=utf-8" });
  saveAs(file);
}
var Upload = function( uploadType ){
  this.uploadType = uploadType;
};
Upload.prototype.delFile = function( id ){
  uploadManager.setExternalState( id, this );
  if( this.fileSize < 300 ){
   return this.dom.parentNode.removeChild( this.dom );
  }
  if( window.confirm('确定要删除该文件吗?' + this.fileName )){
     return this.dom.parentNode.removeChild( this.dom);
  }
};
var UploadFactory = (function(){
  var createdFlyWeightObjs = {};
  return {
    create: function( uploadType ){
      if(createFlyWeightObjs[uploadType]){
        return createdFlyWeightObjs[uploadType];
      }
      return createdFlyWeightObjs[uploadType] = new Upload(uploadType);
    }
  }
})();
var uploadManager = (function(){
  var uploadDatabase = {};
  return{
    add: function(id, uploadType, fileName, fileSize){
      var flyWeightObj = UploadFactory.create( uploadType );
      var dom = document.createElement( 'div' );
      dom.innerHTML = '文件名称:'+fileName+',文件大小:' +fileSize + '' + '<button class="delFile">删除</button>';
      dom.querySelector( ".delFile" ).onclick = function(){
       flyWeightObj.delFile( id );
       document.body.appendChild( dom );
       uploadDatabase[ id ] = {
         fileName: fileName,
         fileSize: fileSize,
         dom: dom
       };
       return flyWeightObj;
     },
     setExternalState: functon( id, flyWeightObj ){
        var uploadData = uploadDatabase[ id ];
        for( var i in uploadData){
           flyWeightObj[ i ] = uploadData[ i ];
        }
     }
  }
})();

在三个有个别有一点点逼格的网址中,那样二个体制实在是有一点点损失形象了,而且要是急需在近期加三个输入框来呈现文件名的话,那暗许的展现文件名的区域怎么隐藏掉呢?别急,继续看:

本条示例是向地面存款和储蓄二个名字叫“手提式有线话机号.txt”的文件文件,选取的字符编码格式为“UTF-8”,这样就幸免的国语乱码的主题素材。聪明的你也尽快试试啊!

下一场供给写多个接触上传动作的startUpload函数:

用3个a标签包住input标签,然后把input标签的opacity设为0,就足以了嘛!ok,看代码:

附 FileSaver.js
文件的总体源码:

var id = o;
window.startUpload = function( uploadType, files ){
  for( var i=0,file; file = fules[ i ++ ];){
     var uploadObj = uploadManger.add( ++id, uploadType, file.fileName, file.fileSize );
  }
};

html:

/* FileSaver.js
 * A saveAs() FileSaver implementation.
 * 1.3.2
 * 2016-06-16 18:25:19
 *
 * By Eli Grey, http://eligrey.com
 * License: MIT
 *  See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
 */
/*global self */
/*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */
/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
var saveAs = saveAs || (function(view) {
  "use strict";
  // IE <10 is explicitly unsupported
  if (typeof view === "undefined" || typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) {
    return;
  }
  var
     doc = view.document
     // only get URL when necessary in case Blob.js hasn't overridden it yet
    , get_URL = function() {
      return view.URL || view.webkitURL || view;
    }
    , save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a")
    , can_use_save_link = "download" in save_link
    , click = function(node) {
      var event = new MouseEvent("click");
      node.dispatchEvent(event);
    }
    , is_safari = /constructor/i.test(view.HTMLElement) || view.safari
    , is_chrome_ios =/CriOS\/[\d]+/.test(navigator.userAgent)
    , throw_outside = function(ex) {
      (view.setImmediate || view.setTimeout)(function() {
        throw ex;
      }, 0);
    }
    , force_saveable_type = "application/octet-stream"
    // the Blob API is fundamentally broken as there is no "downloadfinished" event to subscribe to
    , arbitrary_revoke_timeout = 1000 * 40 // in ms
    , revoke = function(file) {
      var revoker = function() {
        if (typeof file === "string") { // file is an object URL
          get_URL().revokeObjectURL(file);
        } else { // file is a File
          file.remove();
        }
      };
      setTimeout(revoker, arbitrary_revoke_timeout);
    }
    , dispatch = function(filesaver, event_types, event) {
      event_types = [].concat(event_types);
      var i = event_types.length;
      while (i--) {
        var listener = filesaver["on" + event_types[i]];
        if (typeof listener === "function") {
          try {
            listener.call(filesaver, event || filesaver);
          } catch (ex) {
            throw_outside(ex);
          }
        }
      }
    }
    , auto_bom = function(blob) {
      // prepend BOM for UTF-8 XML and text/* types (including HTML)
      // note: your browser will automatically convert UTF-16 U+FEFF to EF BB BF
      if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
        return new Blob([String.fromCharCode(0xFEFF), blob], {type: blob.type});
      }
      return blob;
    }
    , FileSaver = function(blob, name, no_auto_bom) {
      if (!no_auto_bom) {
        blob = auto_bom(blob);
      }
      // First try a.download, then web filesystem, then object URLs
      var
         filesaver = this
        , type = blob.type
        , force = type === force_saveable_type
        , object_url
        , dispatch_all = function() {
          dispatch(filesaver, "writestart progress write writeend".split(" "));
        }
        // on any filesys errors revert to saving with object URLs
        , fs_error = function() {
          if ((is_chrome_ios || (force && is_safari)) && view.FileReader) {
            // Safari doesn't allow downloading of blob urls
            var reader = new FileReader();
            reader.onloadend = function() {
              var url = is_chrome_ios ? reader.result : reader.result.replace(/^data:[^;]*;/, 'data:attachment/file;');
              var popup = view.open(url, '_blank');
              if(!popup) view.location.href = url;
              url=undefined; // release reference before dispatching
              filesaver.readyState = filesaver.DONE;
              dispatch_all();
            };
            reader.readAsDataURL(blob);
            filesaver.readyState = filesaver.INIT;
            return;
          }
          // don't create more object URLs than needed
          if (!object_url) {
            object_url = get_URL().createObjectURL(blob);
          }
          if (force) {
            view.location.href = object_url;
          } else {
            var opened = view.open(object_url, "_blank");
            if (!opened) {
              // Apple does not allow window.open, see https://developer.apple.com/library/safari/documentation/Tools/Conceptual/SafariExtensionGuide/WorkingwithWindowsandTabs/WorkingwithWindowsandTabs.html
              view.location.href = object_url;
            }
          }
          filesaver.readyState = filesaver.DONE;
          dispatch_all();
          revoke(object_url);
        }
      ;
      filesaver.readyState = filesaver.INIT;
      if (can_use_save_link) {
        object_url = get_URL().createObjectURL(blob);
        setTimeout(function() {
          save_link.href = object_url;
          save_link.download = name;
          click(save_link);
          dispatch_all();
          revoke(object_url);
          filesaver.readyState = filesaver.DONE;
        });
        return;
      }
      fs_error();
    }
    , FS_proto = FileSaver.prototype
    , saveAs = function(blob, name, no_auto_bom) {
      return new FileSaver(blob, name || blob.name || "download", no_auto_bom);
    }
  ;
  // IE 10+ (native saveAs)
  if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) {
    return function(blob, name, no_auto_bom) {
      name = name || blob.name || "download";
      if (!no_auto_bom) {
        blob = auto_bom(blob);
      }
      return navigator.msSaveOrOpenBlob(blob, name);
    };
  }
  FS_proto.abort = function(){};
  FS_proto.readyState = FS_proto.INIT = 0;
  FS_proto.WRITING = 1;
  FS_proto.DONE = 2;
  FS_proto.error =
  FS_proto.onwritestart =
  FS_proto.onprogress =
  FS_proto.onwrite =
  FS_proto.onabort =
  FS_proto.onerror =
  FS_proto.onwriteend =
    null;
  return saveAs;
}(
    typeof self !== "undefined" && self
  || typeof window !== "undefined" && window
  || this.content
));
// `self` is undefined in Firefox for Android content script context
// while `this` is nsIContentFrameMessageManager
// with an attribute `content` that corresponds to the window
if (typeof module !== "undefined" && module.exports) {
 module.exports.saveAs = saveAs;
} else if ((typeof define !== "undefined" && define !== null) && (define.amd !== null)) {
 define("FileSaver.js", function() {
  return saveAs;
 });
}

末段调用,如下:

 <div>
 <input class="filename" type="text" readonly="readonly" />
 <a href="javascript:;" name="file">
  <input type="file" name="key"/>浏览
 </a>
 </div>
 <div>
 <input class="filename" type="text" readonly="readonly" />
 <a href="javascript:;" name="file">
  <input type="file" name="key"/>浏览
 </a>
 </div>

PS:本站在线工具上边工具中的很多文件下载功能都以凭借FileSaver.js插件达成的,感兴趣的朋友能够查找参考一下。

startUpload( 'plugin', [
  {
    fileName: '1.txt',
    fileSize: 1000
   },
   {
     fileName: '2.html',
     fileSize: 1000
   },
   {
     fileName: '3.txt',
     fileSize: 5000
   }
]);
startUpload( 'flash', [
  {
    fileName: '4.txt',
    fileSize: 1000
   },
   {
     fileName: '5.html',
     fileSize: 1000
   },
   {
     fileName: '6.txt',
     fileSize: 5000
   }
]);

然后是css文件:

越来越多关于JavaScript相关内容感兴趣的读者可查阅本站专项论题:《JavaScript文件与目录操作技艺汇总》、《JavaScript查找算法本领总括》、《JavaScript数据结构与算法本事统计》、《JavaScript遍历算法与技巧总括》、《JavaScript错误与调整工夫计算》及《JavaScript数学生运动算用法总括》

四、解释:

.filename{
 width: 300px;
 height: 30px;
 line-height: 30px;
}
a{
 width: 50px;
 text-align: center;
 height: 30px;
 line-height: 30px;
 position: raletive;
 cursor: pointer;
 overflow:hidden;
 display: inline-block;
}
a input{
 position: absolute:
 left: 0;
 top: 0;
 opacity: 0;
}

期待本文所述对我们JavaScript程序设计有所补助。

调用时,有两个对象,但唯有七个种类(plugin和flash),我们经过享元方式,在创建对象时,只有五个,要是上边提到的上传3000个文件,利用方面包车型地铁代码,同样只创立八个对象,那么那就很好的缓慢解决了浏览器崩溃假死的主题材料。

马到功成了!!!你看到的样式就变成了如此了,见下图:

你可能感兴趣的篇章:

  • Node.js readline
    逐行读取、写入文件内容的演示
  • Javascript写入txt和读取txt文件示例
  • jscript读写2进制文件的办法
  • JavaScript使用FileSystemObject对象写入文本文件内容的诀窍
  • javascript写的异步加载js文件函数(协理数组传参)
  • JS基于FileSaver.js插件实现文件保留功效示例
  • js基于FileSaver.js
    浏览器导出Excel文件的演示
  • 用JS在浏览器中创立下载文件
  • javascript
    保存文件到本地达成格局
  • JavaScript中读取和保留文件实例

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图