const router = require('koa-router')() const fs = require('fs') , crypto = require('crypto') // 全局路由 router.prefix('/fileStorage') router.get('/', async (ctx, next) => { await ctx.render('index', { title: 'Hello Koa 2!' }) }) let readFileMd5 = (url) =>{ return new Promise((reslove) => { let md5sum = crypto.createHash('md5'); let stream = fs.createReadStream(url); stream.on('data', function(chunk) { md5sum.update(chunk); }); stream.on('end', function() { let fileMd5 = md5sum.digest('hex'); reslove(fileMd5); }) }) } router.post('/putfile', async (ctx) => { const arg = ctx.request.body const file = ctx.request.files.file if(file instanceof Array){ return ctx.body = { message:'上传失败,不支持多文件。', status:'error', }; }else if(!file){ return ctx.body = { message:'上传失败,文件不存在。', status:'error', }; } console.log(file.newFilename) console.log(arg.md5) const md5 = await readFileMd5(file.filepath) console.log(md5) if(md5 == arg.md5){ const createTime = new Date().getTime() const [rows, fields] = await global.SQL.execute('SELECT * FROM `file` WHERE `md5` = ?', [arg.md5]); let filename = createTime.toString() + parseInt(Math.random() * 10000000000000).toString(16) +'.'+ file.newFilename.split('.').slice(-1) if(rows.length == 0){ await global.SQL.execute('INSERT INTO `file` (md5, filename, createTime, filesize) VALUES (?, ?, ?, ?)', [arg.md5, filename, createTime, file.size]); const reader = fs.createReadStream(file.filepath); // 创建可读流 const upStream = fs.createWriteStream(global.dirname + '/fileStorage/' + filename); // 创建可写流 reader.pipe(upStream); // 可读流通过管道写入可写流 }else{ filename = rows[0].filename } return ctx.body = { message:'上传成功', state: true, data:{ md5, filename } }; }else{ return ctx.body = { message:'文件损坏', state:false, }; } // const file = ctx.request.files.file; // 获取上传文件 // const reader = fs.createReadStream(file.filepath); // 创建可读流 // const upStream = fs.createWriteStream('./StaticFile_Backup/' + ctx.request.body.dirname + '/' + ctx.request.body.key); // 创建可写流 // reader.pipe(upStream); // 可读流通过管道写入可写流 }); router.get('/string', async (ctx, next) => { ctx.body = 'koa2 string' }) router.get('/json', async (ctx, next) => { ctx.body = { title: 'koa2 json' } }) module.exports = router