How to upload an image to the backend

Asked

Viewed 4,009 times

3

I have an application in React that sends an image to the backend in Ode the problem is that I can’t get the file in express. I see you have a way to use the woman, only I don’t know how to get the file to the Mgur call. I basically need to send the fron-end pro backend file and pass this file to the Imgur api. hand found no way to recover that image in backend.

To explain better, I can save the files locally with multer, the problem is that I need the backend to send this image to another api, which only accepts acquisitions and not Base64. My problem is there, how can I pass this pick up this file in the backend.

On the front I use the Axios and Formdata, but on the back I don’t know how to get this file, to pass the other api.

  • So as I said in the reply, just indicate the relative path of the file and go through Imgur https://www.npmjs.com/package/imgur#uploading-files-globbing-supported maybe the part of sending pro Imgur is clearer here I edited my answer if you think that

2 answers

3


So , to start you will need to use a static folder you can do this with express, if you do not have the module still use this

npm init -y
npm i -S [email protected]

Declare the static folder

const express = require('express')
    , app = express();

app.use(express.static('caminho_da_pasta'));
app.listen(numero_da_porta, () => console.log('App na porta numero_da_porta'));

Now to use the multer:

const multer = require('multer');
const upload = multer({ dest: 'pasta_de_rececao/' });

//upload com um POST

app.post('caminho_dentro_da_pasta_estatica', upload.single('nome_da_tag'), 
    (req, res) => res.send('Sucesso'));

upload.single('name_da_tag') indicates that we are interested in the data sent with the name file, the same name used by

<input type="file" name="nome_da_tag">

If you succeed your file will be inside the specified folder only the file name will be different from the original name to have the original name with the extension and need to specify a Storage with the multer also

const storage = multer.diskStorage({
    destination: function (req, file, cb) {

        cb(null, 'pasta_de_rececao/');
    },
    filename: function (req, file, cb) {

        cb(null, `${file.fieldname} + '-' +${path.extname(file.originalname)`})
    }
});



//e em vez de passar a pasta_de_rececao como argumento , passamos a storage
const upload = multer({ storage });

just then pick up the image path + the image name and send with the Imgur module

var imgur = require('imgur');
imgur.setAPIUrl('https://api.imgur.com/');

imgur.uploadFile('/caminho/da/imagem.png')
.then(function (json) {
    console.log(json.data.link);
})
.catch(function (err) {
    console.error(err.message);
});

source:Mgur I hope it helps

  • I updated the question, to clarify my doubt.

  • I have now edited the answer @Lukastakahashi to be more detailed

  • Brigado! this method is functional, but I wonder if I do not want to have the file on my server, every time the User upload I have to save the image, send it to api and delete the image. Have a mode where you don’t need to save the image on my server?

  • As mentioned above, you can encode it in Base64 and send it directly to github

2

Since you are using React, I imagine you will make an Ajax request to move the image to the API. To do this in Javascript use FormData as the excerpt below illustrates:

<form method="post" enctype="multipart/form-data" id="meuForm">
    <input type="file" id="inputImg" />
    <input type="submit" value="Postar" />
</form>

Javascript:

document.getElementById('meuForm').onsubmit = function() {
    const input = document.getElementById('inputImg');
    const file = input.files[0];

    const formData = new FormData();    
    formData.append('anexo', file);
    formData.append('nome', 'teste');
    // TODO chamada AJAX passando o FormData
};

Already in the backend it is necessary to install the multer or another lib parsing forms multipart/form-data. Below is an example that I use in a personal project. I removed some excerpts that are not necessary for your solution:

exports.post = async (req, res) => {
    var multer = require('multer');

    var upload = null;
    try {
        var path = require('path');
        var storage = multer.diskStorage({
            destination: function (req, file, cb) {
                cb(null, process.env.DIRETORIOUPLOAD);
            },
            filename: function (req, file, cb) {
                fileExtension = file.originalname.split('.')[1];
                cb(null, require('crypto')
                    .randomBytes(64).toString('hex') + path.extname(file.originalname));
            }
        });

        upload = multer({ storage: storage }).fields([
            { name: 'anexo', maxCount: 1 }
        ]);
    } catch (ex) {
    // (...)
    }

    upload(req, res, async err => {
        if (err) {
            // (...)
        }

        // Quando o código chegar aqui é porque seu arquivo já 
        // foi salvo no disco. Agora você pode continuar com seu processamento
        // lendo os demais campos postados
        // Demais campos postados:
        const nome = req.body.nome; // Valor 'teste' neste exemplo

        // (...)

        res.json({ ok: 1 });
    });
}
  • I updated the question, to clarify my doubt

  • @Lukastakahashi has now become clearer! Would it be possible to detail a little better how this API is expecting to receive the image? In advance this link may help you: https://stackoverflow.com/questions/48994269/nodejs-binary-data-with-request

  • Thank you for answering, I will take a look at the link and test.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.