1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26-27--28 29---30 31--32 33 34 35 36 37 38-39 40 41 42 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 5 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108-109 |
var extend = require ("Extend"); var fs = require ("FS"); var excelexport = require (' Excel-export '); var guid=require (' GUID '); var path=require (' path '); var excel=function () {this.req=null; this.resp=null;}; /** * Generate Excel File * @param params/excel.prototype.createexcel=function (params) {var Setting={savepath: "uploadfile/ Excel/"}; Setting=extend ({},setting,params); var uuid=guid.create (); var data=params.data| | ""; var result = Excelexport.execute (data); var name= ' Excel ' +uuid+ '. xlsx '; var filepath= path.resolve (Setting.savepath, name); Fs.writefile (FilePath, result, ' binary ', function (err) {SETTING.CB (FilePath);}); /** * Computes last breakpoint information * @param range * @returns {number} * @private/excel.prototype._calstartposition = function (range) {V Ar startpos = 0; if (typeof range!= ' undefined ') {var startposmatch =/^bytes= ([0-9]+)-$/.exec (range); startpos = number (startposmatch[1] ); return startpos; } excel.prototype._configheader = function (config) {var startpos = config.startpos, fileSize = Config.filesize, resp = this.resp; If the startpos is 0, it means that the file was downloaded from 0, otherwise the breakpoint was downloaded. if (startpos = = 0) {resp.setheader (' accept-range ', ' bytes ');} else {resp.setheader (' content-range ', ' bytes ' + startpos + '-' + (fileSize-1) + '/' + fileSize ' +; } resp.writehead (206, ' Partial Content ', {' Content-type ': ' Application/octet-stream '}); } excel.prototype._init = function (FilePath, down) {var config = {}; var self = this; Fs.stat (FilePath, function (error, S Tate) {if (error) throw error; config.filesize = state.size; var range = Self.req.headers.range; config.startpos = Self._c Alstartposition (range); self.config = config; Self._configheader (config); Down (); }); /** * Download File * @param filePath file path * @param req * @param res * @param isdeleted delete files after download is complete, true delete */Excel.prototype.dow nload = function (filepath,req,res,isdeleted) {var self = this; self.req=req; self.resp = res; path.exists (FilePath, funct Ion (exist) {if (exist) {self._init (FilePath, function () {var config = Self.config resp = selF.RESP; Freadstream = Fs.createreadstream (FilePath, {encoding: ' binary ', buffersize:1024 * 1024, Start:config.startPos, end : Config.filesize}); Freadstream.on (' Data ', function (chunk) {resp.write (chunk, ' binary ');}); Freadstream.on (' end '), function () {//whether to delete file if (isdeleted) {fs.unlink (FilePath, function (err, res) {}), Resp.end ();} ); }); } else {console.log (' file does not exist! '); Return } }); } module.exports=new Excel (); |