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: "Ошибка сервера"
})
}
})
handler.ts:
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;
react handlers:
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); // {}
}
input react component:
<MyInput
accept={[".png", ".svg", ".jpg", ".jpeg"]}
multiple={false}
name="coverPhoto"
placeholder="Обложка"
type="file"
onChange={addCoverPhotoHandler}
/>
<MyButton onClick={addProjectHandler}>Опубликовать</MyButton>