Storing the location of the images in the database using `VARCHAR` in ExpressJS & image in server Hard-Disk

StackOverflow https://stackoverflow.com/questions/20213400

  •  05-08-2022
  •  | 
  •  

Pergunta

How I can do this in ExpressJS?

  • Storing the location of the images in the database using VARCHAR datatype instead of any BLOB or other binary datatype.
  • then store that image in server harddisk in possible image space /public/images/

i am new to express .

Any sample example to achieve this ?

Foi útil?

Solução

What you can do is use the multipart middleware, which automatically streams the file uploads to the disk, and then provides a req.files object.

app.use('/upload', express.multipart({ uploadDir: '/public/images' }));

Once you've configured this, in your request handler, you can get the upload path (see multiparty's documentation, which is used internally by the multipart middleware):

app.post('/upload', function (req, res, next) {
  // Assuming the field name of the file in the form is 'file'
  var path = req.files.file.path;
  connection.query('your mysql query', next);
});

Outras dicas

you can try this for upload image you will store only path of image and save that image in your storage

var tempPath = req.files.image.path;
          var ext = path.extname(req.files.image.name).toLowerCase();
          var targetPath = path.resolve('./profile_img/' + user_id + ext);
        //  var targetPath = path.resolve('D:/Alex/Project/img/' + user_id + ext);
        if (ext === '.png' || ext === '.jpg' || ext === '.jpeg' || ext === '.gif')
          {
                        var inStr = fs.createReadStream(tempPath);
                            var outStr = fs.createWriteStream(targetPath);
                            inStr.pipe(outStr);

                            //save profile image to database
                            connection.query('update users set img_path=? where id=?',[targetPath,user_id],
                            function(err,imagesave){
                            if(!err)
                            {

                                    console.log('Profile Picture Uploaded ..');
                                    res.json({'code':200,'status':'Success','message':'Profile Picture Uploaded ..'});
                                    return;
                            }
                            else
                            {
                                    console.log('can not update ..',err);
                                    res.json({'code':200,'status':'Success','message':err});
                                    return;
                            }
                        });
        }
          else
          {
                        console.log('File type must be image',err);
                        res.json(500, {error: 'Only image files are allowed.'});

          }
        }
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top