I've only used koa-bodyparser and I just found out that It doesn't parser form-data that allows to upload files. so I'm trying these modules co-busboy, koa-body, koa-better-body. but I couldn't figure out how to rename the upload file before save it. since I've never done this before I want to know about how to do it. Any ideas?
Asked
Active
Viewed 1,197 times
3 Answers
2
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);
}
}
}));

HAVENT
- 21
- 2
0
That depends on the scope of renaming the file.
If you want to rename the file for uniqueness, then most of the libraries will handle that for you, so you don't have to do anything.
If you want to give it a custom name, you can't do that before upload, but you can easily do it after.
Here is a working example using 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,
}));
Then in your route
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');
})

Valera
- 2,665
- 2
- 16
- 33
0
Probably you'll want to use this:
https://github.com/dlau/koa-body
onFileBegin {Function} Special callback on file begin. The function is executed directly by formidable. It can be used to rename files before saving them to disk. See the docs

Vitaly Mosin
- 61
- 5