Answer the question
In order to leave comments, you need to log in
req.file = undefined?
upload.ts:
import { NextApiResponse } from 'next';
import connectMongo from "../../utils/connectMongo";
import multer from 'multer';
import path from "path";
import handler from './handler';
connectMongo();
export const config = {
api: {
bodyParser: false
}
}
const storage = multer.diskStorage({
destination:(req, file, cb) => {
cb(null, "public/uploads")
},
filename:(req, file, cb) => {
cb(null, file.fieldname + "-" + Date.now + path.extname(file.originalname))
}
})
const uploadImages = multer({ storage });
const uploadFile = uploadImages.single("coverPhoto");
handler.use(uploadFile);
export default handler.post(async(req:any, res:NextApiResponse) => {
try {
const { file } = req;
console.log(file) // undefined
res.status(200).json({
file: file || undefined
})
} catch(e) {
console.log(e);
res.status(500).json({
success: false, message: "Ошибка сервера"
})
}
})
import { NextApiRequest, NextApiResponse } from "next";
import nextConnect from "next-connect";
const handler = nextConnect({
onError(error, req:NextApiRequest, res:NextApiResponse) {
res.status(501).end(`Sorry something Happened! ${error.message}`);
},
onNoMatch(req:NextApiRequest, res:NextApiResponse){
res.status(405).end(`Method ${req.method} Not Allowed`);
}
})
export default handler;
const [addProject, setAddProject] = React.useState<IProject>(projectDefaultState);
const addCoverPhotoHandler = async(event) => {
if (!event.target.files?.length) return;
setAddProject({ ...addProject, coverPhoto: event.target.files[0] });
}
const addProjectHandler = async(event) => {
event.preventDefault();
const response = await fetch(`${process.env.API_URL}/api/upload`, {
method: "POST",
body: JSON.stringify(addProject.coverPhoto)
})
const data = await response.json();
console.log(data); // {}
}
<MyInput
accept={[".png", ".svg", ".jpg", ".jpeg"]}
multiple={false}
name="coverPhoto"
placeholder="Обложка"
type="file"
onChange={addCoverPhotoHandler}
/>
<MyButton onClick={addProjectHandler}>Опубликовать</MyButton>
Answer the question
In order to leave comments, you need to log in
JSON.stringify(addProject.coverPhoto)
What are you expecting to send here? File per line?
The file is submitted via FormData and with the appropriate request header.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question