简体   繁体   中英

process file after uploaded by formidable in node js + express

I am using formidable for uploading files. after the file is completely uploaded, I want to make resized copies of the same using jimp.

previously I was calling the jimp resizer on form.on('end', ...) event but it seems that file was partially uploaded till then and as jimp tries to access it while upload is in progress, the file remains corrupt!

so definitely I need to call jimp after form.on('end', ...) is processed.

here is what I am doing -

app.post("/upload", function (req, res) {
    let form = new IncomingForm()

    var file_path, file_name

    form.on('fileBegin', (name, file) => {
        // process upload here. should be jPG / PNG, smallest edge should be 1200px, compress to 720px and 240px
        // save raw file
        let dt = new Date()
        file_name = dt.getTime() + '.' + file.name.split('.').pop()
        file_path = __dirname + '/upload/raw/' + file_name
        file.path = file_path
    })

    form.on('file', function (name, file) {

    })

    form.on('end', () => {

    })

    form.parse(req)
    resizer(file_path)

    res.json(
        file_name
    )
})

the resizer(file_path) being the function where I am doing all the jimp processing. However this seems to be called asynchronously and thus file does not exist when this is called. async await seems to be useless as this process is event driven. is there a way to call resizer after all the processing is done? or if there is a formidable event for the same?

Seems like calling the function inside callback of form.parse does the trick.

for reference - in the end you should do this -

form.parse(req, (error, field, file) => {
    resizer(file_path)
})

keeping this thread active if someone stumbles upon this situation in future

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM