Handling multipart/form-data images on backend api
Hi, I want to get form data of image and send it do Cloudinary how should I approach it?
multer to parse multipart/form-data.request hook that is called when a request is received.multipart/form-data.. Latest version: 1.4.5-lts.1, last published: 3 years ago. Start using multer in your project by running npm i multer. There are 4883 other projects in the npm registry using multer.
as any. Any way thank you for sources.multerrequestnpm i multerexport default eventHandler(async event => {
const form = await readMultipartFormData(event)
// do stuff
})as anyimport { IncomingMessage } from 'node:http'
import { H3Event } from 'h3'
import multer from 'multer'
import type { Request, Response } from 'express'
const storage = multer.diskStorage({
destination: 'uploads/',
filename: (_req, file, cb) => {
cb(null, `${Date.now()}-${file.originalname}`)
},
})
const upload = multer({ storage })
const useMulter = (event: H3Event): Promise<{
body?: Record<string, unknown>;
file?: Express.Multer.File | undefined
}> => {
return new Promise((resolve, reject) => {
const req = event.node.req as IncomingMessage & Request;
const res = event.node.res as Response;
upload.any()(req, res, (err: any) => {
if (err) {
reject(err);
return;
}
resolve({
body: req.body,
file: req.file,
});
});
});
};
export default defineEventHandler(async (event) => {
try {
const { file, body } = await useMulter(event);
if (file) {
console.log('File uploaded:', file.path);
}
console.log('Body:', body);
return { success: true, message: 'File uploaded successfully', body, file };
} catch (error) {
console.error('Upload error:', error);
throw createError({ statusCode: 500, message: 'File upload failed', data: error });
}
});// server/api/upload.post.ts
import { defineEventHandler } from 'h3'
export default defineEventHandler(async (event) => {
try {
// Read the body of the request
const body = await readBody(event)
// Here you would typically handle the file data
// This is where you'd process the image and send it to Cloudinary
// However, the exact implementation depends on how you're sending the data
// and what libraries you're using for multipart parsing
// For example, if the image is sent as base64:
// const imageData = body.image
// Process the image (send to Cloudinary, etc.)
// const result = await sendToCloudinary(imageData)
return { success: true, message: 'Image uploaded successfully' }
} catch (error) {
return { success: false, message: error.message }
}
})const { file, body } = await useMulter(event).catch(() => {
throw createError({ statusCode: 500, message: 'File upload failed' })
})const useMulter = (event: H3Event): Promise<{ file?: Express.Multer.File; body?: Record<string, unknown> }> => {
return new Promise((resolve) => {
// Run multer middleware
// eslint-disable-next-line
middleware(event.node.req as any , event.node.res as any, (er) => {
if (er) {
throw er
}
resolve({
// eslint-disable-next-line
body: (event.node.req as any).body,
// eslint-disable-next-line
file: (event.node.req as any).file,
})
})
})
}import type { H3Event } from 'h3'
import type { IncomingMessage } from 'node:http'
import multer from 'multer'
import fs from 'fs'
const middleware = multer({ dest: 'tmp/', limits: { fileSize: 5 * 1024 * 1024 } }).single('image')
/**
* Middleware function to handle file uploads using Multer.
*
* @param {H3Event} event - The event object from H3.
* @returns {Promise<{ file?: Express.Multer.File, body?: Record<string, any> }>} - A promise that resolves with the uploaded file and request body.
*/
const useMulter = async (event: H3Event): Promise<{
file?: Express.Multer.File | undefined,
body?: Record<string, unknown>,
}> => {
return new Promise((resolve, reject) => {
// eslint-disable-next-line
const req = event.node.req as IncomingMessage & any
// eslint-disable-next-line
const res = event.node.res as any
// Run multer middleware
// eslint-disable-next-line
middleware(req, res, (er: any) => {
if (er) {
reject(er)
return
}
resolve({
body: req.body,
file: req.file,
})
})
})
}
/**
* Delete a tmp from file system.
*
* @param filePath - Path to the file to be deleted.
*/
const deleteMulterFile = (filePath: string): void => {
fs.unlink(filePath, (err) => {
if (err) {
console.error('Error deleting the file:', err)
}
})
}
export { useMulter, deleteMulterFile }