Ehtesham Siddiqui
Ehtesham Siddiqui

Reputation: 37

Error using fastify-multer to upload images

I am trying to use the fastify-multer plugin to upload files to the server and I am able to successfully get the images uploaded to the folder. The problem is my app crashes. I used the fastify-cli generated structure and I am running it as a standalone server as mentioned in the README.md here.

I am writing it as a fastify plugin.

"use strict";

const fp = require("fastify-plugin");

module.exports = fp(function(fastify, opts, next) {
  fastify.decorate("uploadImage", function(request) {
    const path = require("path");
    const multer = require("fastify-multer");

    var storage = multer.diskStorage({
      destination: path.join(path.join(__dirname + "/uploads/")),
      filename: function(request, file, cb) {
        cb(null, file.originalname);
      }
    });

    var upload = multer({ storage }).single("myImage");
    upload(request, function(err) {
      if (err) {
        console.log(err);
      } else {
        console.log("Saved...");
        return { saved: true };
      }
    });
  });
  next();
});

And here is the error I get : enter image description here

Upvotes: 0

Views: 4432

Answers (1)

Maksim
Maksim

Reputation: 215

Hi looked into your issue. You are using fastify-multer in the wrong way. Invoking multer({ storage }).single("myImage") you are creating a fastify's preHandler hook that accepts 3 specific parameters. You can find more on the offical documentation. A simple working example could be the one you can see at fastify-multer:

const server = fastify()
// register fastify content parser
server.register(multer.contentParser)

server.route({
  method: 'POST',
  url: '/profile',
  preHandler: upload.single('avatar'),
  handler: function(request, reply) {
    // request.file is the `avatar` file
    // request.body will hold the text fields, if there were any
    reply.code(200).send('SUCCESS')
  }
})

If you need more help just provide me a repro repo on github and I'll try to figure out what is the best solution for your case.

Let me know! :)

Upvotes: 2

Related Questions