Ashok Singh
Ashok Singh

Reputation: 41

How to make few routes use app.register(require("fastify-multipart"), { addToBody: true }); and other use app.register(require("fastify-multipart"))

I am trying to send image in multipart form data for few routes because I wish to use request.multipart function.

I have used app.register(require("fastify-multipart") ), { addToBody: true }) for all routes but for routes having image (starting like /image/*) I want to get multipart data not in body.

please guide me to get the solution for this, I am trying this for quite some time now but didn't find any solution.

//creating fastify server and add below plugin
app.register(require("fastify-multipart"), { addToBody: true });
app.get("/health", (_, reply) => reply.send("Congratulations! reverse proxy is working....."));

app.route({
  method: ["DELETE", "GET", "HEAD", "PATCH", "POST", "PUT"],
  url: "*",
  handler: handler,
})

handler for /image/upload is

handler : async (request) => {
 const formData = new FormData();
    const multipart = request.multipart(async (field, stream, filename, encoding, mimetype) => {
      formData.append('image', stream);

  try {
          
        const data = await axios.post(`http:127.0.0.1:80/downstream`, formData, config )  
        console.log("upload success with url", data)  
      }
      catch(e) {
          console.log(`An error occurred during upload: ${e.message}`)
           reply.code(500).send()
      }
  }, (error) => {

      if(error) {
          console.log(`Error uploading file: ${error.message}`)
           reply.code(500).send()
      } 
  })
}

this above handler work when I remove { addToBody: true } from app.register(require("fastify-multipart"), { addToBody: true }) plugin i.e app.register(require("fastify-multipart")) because req.multipart handler only works on stream that's why adding image to body doesn't work.

Upvotes: 2

Views: 754

Answers (0)

Related Questions