You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
md5file/routes/fileStorage.js

67 lines
1.8 KiB

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'
})
router.get('/json', async (ctx, next) => {
ctx.body = {
title: 'koa2 json'
}
})
module.exports = router