diff --git a/app.js b/app.js index 0ef9d84..9849534 100644 --- a/app.js +++ b/app.js @@ -8,6 +8,7 @@ const {koaBody} = require('koa-body')// 支持form-data,支持文件,不 const index = require('./routes/index') const users = require('./routes/users') +const fileStorage = require('./routes/fileStorage') // error handler onerror(app) @@ -46,6 +47,7 @@ app.use(koaBody({ // routes app.use(index.routes(), index.allowedMethods()) app.use(users.routes(), users.allowedMethods()) +app.use(fileStorage.routes(), fileStorage.allowedMethods()) // error-handling app.on('error', (err, ctx) => { diff --git a/routes/fileStorage.js b/routes/fileStorage.js index ad658af..4e16b7c 100644 --- a/routes/fileStorage.js +++ b/routes/fileStorage.js @@ -1,11 +1,59 @@ 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', + }; + } + const md5 = await readFileMd5(file.filepath) + + // 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); // 可读流通过管道写入可写流 + return ctx.body = { + message:'上传成功', + status:'ok', + data:{ + md5 + } + }; +}); + router.get('/string', async (ctx, next) => { ctx.body = 'koa2 string' }) diff --git a/systemConfig.js b/systemConfig.js new file mode 100644 index 0000000..75b89ff --- /dev/null +++ b/systemConfig.js @@ -0,0 +1,13 @@ +module.export = { + systemName:'rgvFileMD5Storage', + fileSavePath:'', + fileMaxSize:'', + database:{ + host:'', + port:'', + user:'', + pass:'', + name:'' + }, + +} \ No newline at end of file