E
E
embiid2020-06-06 06:57:44
Node.js
embiid, 2020-06-06 06:57:44

How to convert an uploaded file into a post request?

I'm already asking this question for the second or third time)

I'm making an application that should take an image and compress it. For loading I use multer and for compression I would like imagemin.

Here, for example, I load here and then display this picture with the get-parameter

router.post('/upload', (request, response) => {
    upload(request, response, (error) => {
        if(error) {
            request.flash('error_message', 'Only images are allowed')
            response.redirect('/')
        }
        else {
            if(request.file == undefined) {
                request.flash('error_message', 'Image file was not been selected.')
                response.redirect('/')

                console.log(request.file)
            }
            else {
                request.flash('success_message', 'Image was uploaded successfully.')
                response.redirect(`/${request.file.filename}`);

                console.log(request.file)
            }
        }
    })
})

router.get('/:filename', (request, response) => {
    let fileName = request.params.filename

    let pathToCheck = path.join(__dirname, '../public/uploads/' + fileName)
    if (fs.existsSync(pathToCheck)) {
        let imageDestination = `${request.protocol}://${request.headers.host}/uploads/${fileName}`;
        response.render('compress', {
            userImage: imageDestination
        })
    }
    else {
        response.send('Oops.')
    }
})


Then I want THIS image that was uploaded via post "upload" or that is displayed in get "/:filename" was compressed:

router.post('/compress/:filename', async (request, response) => {
    const compressedImage = await imagemin([request.params.filename], {
        destination: 'compressed',
        plugins: [
            imageminMozjpeg(),
            imageminJpegtran(),

            imageminPngquant(),
            imageminOptipng(),

            imageminGiflossy(),
            imageminGifsicle(),

            imageminSvgo(),
            imageminWebp()
        ]
    })

    request.flash('success_message', 'Image was compressed successfully. Now it is ready to be downloaded.')
    response.redirect('result')
})


But I get "Cannot POST /compress/" in response.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question