123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- 'use strict';
- const Controller = require('egg').Controller;
- const path = require('path');
- const awaitWriteStream = require('await-stream-ready').write;
- const sendToWormhole = require('stream-wormhole');
- const fs = require('fs');
- class BaseController extends Controller {
-
- async _uploadOne(savePath,filename) {
- let that = this;
- filename = filename || (that.app.szjcomo.date('YmdHis') + '' + that.app.szjcomo.mt_rand(100000,999999));
- return await that._uploadHandler(await that.ctx.getFileStream(),savePath,filename);
- }
-
- async _uploadAll(savePath) {
- let that = this;
- let part;
- let result = [];
- let fields = {};
- let parts = await that.ctx.multipart();
- while ((part = await parts()) != null) {
- if (part.length) {
- fields[part[0]] = part[1];
- } else {
-
- let filename = (that.app.szjcomo.date('YmdHis') + '' + that.app.szjcomo.mt_rand(100000,999999));
-
- result.push(await that._uploadHandler(part,savePath,filename));
- }
- }
- return result;
- }
-
- async _uploadHandler(stream,savePath,filename){
- let that = this;
- let ext = path.extname(filename);
- if(that.app.szjcomo.empty(ext)) filename += path.extname(stream.filename);
-
- that.app.szjcomo.mkdir(savePath);
-
- let target = path.join(savePath, filename);
-
- let writeStream = fs.createWriteStream(target);
- try{
-
- await awaitWriteStream(stream.pipe(writeStream));
- } catch(err){
-
- await sendToWormhole(stream);
- throw err;
- }
- await sendToWormhole(stream);
- return {save_path:savePath,save_name:filename,file_sha1:that.app.szjcomo.FileSHA1(target),
- fields:stream.fields,file_size:writeStream.bytesWritten,mime:stream.mime,encoding:stream.encoding,
- origin_name:stream.filename,file_md5:that.app.szjcomo.FileMD5(target),ext:path.extname(stream.filename)}
- }
-
- async logs(fileName,err) {
- let that = this;
- let filePath = `${that.app.baseDir}/logs/${that.app.szjcomo.date('Y-m-d')}`;
- fileName = fileName + '.txt';
- await that.app.szjcomo.mkdir(filePath);
- let isFile = await that.service.base.fileExists(path.join(filePath,fileName));
- let filedata = `=========${that.app.szjcomo.date('Y-m-d H:i:s')}==========\r\n${err.stack}\r\n=========${that.app.szjcomo.date('Y-m-d H:i:s')}==========\r\n\r\n`;
- if(isFile) {
- fs.appendFileSync(path.join(filePath,fileName),filedata);
- } else {
- fs.writeFileSync(path.join(filePath,fileName), filedata);
- }
- }
- }
- module.exports = BaseController;
|