I'm trying to upload a file to a NodeJS server using the formidable module. After the upload I'd like to rename the file to something else, for which I need to get the name and path of the uploaded file. As per the documentation provided by formidable, you have to call the Formidable.File class to get the file path which is where the file is being written.
Here's the documentation: https://github.com/felixge/node-formidable#formidableincomingform
My project is written in Typescript, so I've written a Typescript definition for Formidable which includes only those literals that I need to call. That is called in another file Upload.ts
Here's the typescript definition for formidable
declare module "formidable" {
export class IncomingForm{
uploadDir: String;
keepExtensions: Boolean;
type: String;
parse(req, Function) : void;
}
export class File{
name: String;
path: String;
}
}
Upload.ts
public upload(req, res){
var form = new formidable.IncomingForm();
var file = new formidable.File();
var originalFileName = file.name;
form.uploadDir = this.directory;
form.keepExtensions = true;
form.type = 'multipart';
form.parse(req, function(err, fields, files) {
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received upload:\n\n');
res.end(util.inspect({fields: fields, files: files}));
});
return;
}
When I hit the "upload" button it results in an error that says:
var file = new formidable.File();
TypeError: undefined is not a function
My definition seems correct as per the documentation, and I don't understand this error.
You can't get the path of an uploaded file by creating a new empty File instance.
The files parameter in your callback to the parse method contains the File objects of the uploaded files.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With