Scala
PPrisma
•Created by Scala on 6/3/2024 in #help-and-questions
Uploading image
Anyone can help me with uploading images to the server? I did this using nulter but keep getting 500 interal server error when trying to make the post reqest on postman by uploading an image
import express, { Express, Request, Response } from 'express'
import { PORT } from './secrets'
import rootRouter from './routes'
import { PrismaClient } from '@prisma/client'
import { errorMiddleware } from './middlewares/errors'
declare global {
namespace Express {
interface Request {
file?: Express.Multer.File;
}
}
}
const app:Express = express()
const path = require('path')
const cors = require('cors');
const multer = require('multer')
const storage = multer.diskStorage({
destination: (req: Request, file: Express.Multer.File, cb: (error: Error | null, destination: string) => void) => {
cb(null, 'Images')
},
filename: (req: Request, file: Express.Multer.File, cb: (error: Error | null, destination: string) => void) => {
console.log(file);
cb(null, Date.now() + path.extname(file.originalname))
}
})
const upload = multer({storage: storage})
app.use(express.json())
app.use(cors())
app.post('/upload', upload.single('image'), (req: Request, res: Response) => {
if (!req.file) {
return res.status(400).json({ error: 'No file uploaded' });
}
res.json({ message: 'Image uploaded', file: req.file });
})
app.use('/', rootRouter)
export const prismaClient = new PrismaClient({
log:['query']
})
app.use(errorMiddleware)
app.listen(PORT, () => {
console.log('Working');
})
import express, { Express, Request, Response } from 'express'
import { PORT } from './secrets'
import rootRouter from './routes'
import { PrismaClient } from '@prisma/client'
import { errorMiddleware } from './middlewares/errors'
declare global {
namespace Express {
interface Request {
file?: Express.Multer.File;
}
}
}
const app:Express = express()
const path = require('path')
const cors = require('cors');
const multer = require('multer')
const storage = multer.diskStorage({
destination: (req: Request, file: Express.Multer.File, cb: (error: Error | null, destination: string) => void) => {
cb(null, 'Images')
},
filename: (req: Request, file: Express.Multer.File, cb: (error: Error | null, destination: string) => void) => {
console.log(file);
cb(null, Date.now() + path.extname(file.originalname))
}
})
const upload = multer({storage: storage})
app.use(express.json())
app.use(cors())
app.post('/upload', upload.single('image'), (req: Request, res: Response) => {
if (!req.file) {
return res.status(400).json({ error: 'No file uploaded' });
}
res.json({ message: 'Image uploaded', file: req.file });
})
app.use('/', rootRouter)
export const prismaClient = new PrismaClient({
log:['query']
})
app.use(errorMiddleware)
app.listen(PORT, () => {
console.log('Working');
})
2 replies