0

On the frontend I'm uploading the image using FormData

const formData = new FormData();
formData.append('avatar', data.file);
return API.post('/uploadImg', formData)

On the backend I am using express and have the next function

async function uploadImg(req, res) {
    req.pipe(req.busboy)
    req.busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
        const fstream = fs.createWriteStream(path.join("thestorage",`/image.${mimetype}` ))
        file.pipe(fstream)
        fstream.on('close', async (error, data) => {
            res.status(200).send({ message: 'Image was uploaded'})
        })
    }  
}

I want to split the logic on the backend, so uploadImg function will only manage the request and the actual file management would be in the separate function. How do I pass the file stream to other function?

I've tried so far:

async function uploadImg(req, res) {
    await theUpload(req.headers)
    res.status(200).send({ message: 'Image was uploaded'})
}

async function theUpload(headers) {
    let bus_boy = new Busboy({headers: headers})
    bus_boy.on('file', function (fieldname, file, filename, encoding, mimetype) {
        const fstream = fs.createWriteStream(path.join("thestorage",`/image.${mimetype}` ))
        file.pipe(fstream)
        fstream.on('close', async (error, data) => {
            console.log('done')
        })
    }  
}
Nikita Lvov
  • 97
  • 2
  • 14

0 Answers0