我只使用了koa-bodyparser,并且我刚刚发现它不能解析允许上传文件的表单数据。所以我尝试了co-busboy,koa-body,koa-better-body这些模块。但是我不知道如何在保存之前重命名上传的文件。因为我以前从来没有这样做过,所以我想知道怎么做。有什么想法吗?
发布于 2018-09-17 16:49:55
app.use(koaBody({
multipart:true,
encoding:'gzip',
formidable:{
uploadDir:path.join(__dirname,'public/upload'),
keepExtensions: true,
maxFieldsSize:2 * 1024 * 1024,
onFileBegin:(name,file) => {
const dir = path.join(__dirname,`public/upload/}`);
file.path = `${dir}/newPath/newFileName.png`;
},
onError:(err)=>{
console.log(err);
}
}
}));
发布于 2017-07-25 06:45:05
这取决于重命名文件的范围。
如果您想要重命名文件以保证唯一性,那么大多数库都将为您处理此问题,因此您无需执行任何操作。
如果你想给它一个自定义名称,你不能在上传之前这样做,但你可以很容易地在上传之后这样做。
下面是一个使用koa-body的工作示例
// use this as first middleware
app.use(require('koa-body')({
formidable: {
uploadDir: __dirname + '/public/uploads', // upload directory
keepExtensions: true // keep file extensions
},
multipart: true,
urlencoded: true,
}));然后在你的路线上
router.post('/upload-file', async function (ctx, next) {
// file_param is the request parameter name
let filePath = ctx.request.body.files.file_param.path
// rename file
fs.renameSync(filePath , '/path/to/your_new_file');
})发布于 2018-05-26 22:50:25
您可能会想要使用以下代码:
https://github.com/dlau/koa-body
函数{ onFileBegin }文件开始时的特殊回调。该函数由formidable直接执行。它可用于在将文件保存到磁盘之前对文件进行重命名。See the docs
https://stackoverflow.com/questions/45107821
复制相似问题