pac
pac

Reputation: 241

Node JS Create link from picture to database

I want to create a link (./pictures) of a picture which is already uploaded and add the link to my MySQL-DB.

Picture Save:

var Storage = multer.diskStorage({
    destination: function(req, file, callback) {
        callback(null, "./pictures");
    },
    filename: function(req, file, callback) {
        pictureSaveFormat = Date.now();
file.originalname);
        callback(null, pictureSaveFormat + ".jpg");
    }
});

Upvotes: 2

Views: 448

Answers (1)

Waseem
Waseem

Reputation: 751

This only pseudo/example code but I hope it helps:

const storage = multer.diskStorage({
  destination(req, file, cb) { /* save to destination */},
  filename(req, file, cb) { /* make filename */ }
});

router.post('/', multer({ storage }), (req, res) => {
  // you can store all these params
  const fileAttrs = {
    fieldname: req.file.fieldname,
    originalname: req.file.originalname,
    encoding: req.file.encoding,
    mimetype: req.file.mimetype,
    destination: req.file.destination,
    filename: req.file.filename,
    path: req.file.path,
    size: req.file.size
  }
  // save fileAttrs into your database (e.g. using Photo model)
  Photo.create(fileAttrs).then(() => {
    // handle response
    res.redirect('/');
  });
}); 

The main idea is that you may want to create the storage middleware and pass it to your route handler. Once an image is uploaded you should have access to a number or attributes that can be stored in the database and used later to retrieve the image.

As for storing the attributes in the database, I'm going to assume that you're using some sort of ORM such bookshelf or sequelize. In which case, you'll have a photo/image model that can be used to write those attrs to the database.

All of that needs to be done in your route handler before handling the response.

Upvotes: 1

Related Questions