🚀
【Web Library】Nextjs13で覚える便利なライブラリ【#16image submit】
【#16image submit】
YouTube: https://youtu.be/E9XLGu9tUNk
今回は画像の送信とAPIルートの作成を行います。
app/upload/page.tsx
'use client';
import Image from 'next/image';
import React, { ChangeEvent, SyntheticEvent, useState } from 'react';
const Page = () => {
const [images, setImages] = useState([]);
const handleSubmit = async (e: SyntheticEvent) => {
e.preventDefault();
const formData = {
images,
};
const res = await fetch(`/api/upload`, {
method: 'POST',
body: JSON.stringify(formData),
});
const data = await res.json();
console.log(data);
};
const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
// objectURL = URL.createObjectURL(object);
const files = Array.from(e.target.files as FileList);
files.forEach((file) => {
const reader = new FileReader();
reader.onload = () => {
if (reader.readyState === 2) {
setImages([...images, reader.result] as any);
}
};
reader.readAsDataURL(file);
});
};
return (
<div className="text-white">
<form
encType="multipart/form-data"
className="flex flex-col items-center gap-2"
onSubmit={handleSubmit}
>
<input
type="file"
name="upload_image"
onChange={handleChange}
multiple
accept="image/*"
/>
<div className="flex flex-wrap gap-2">
{images.map((img) => (
<Image
src={img}
key={img}
alt="preview image"
width="100"
height="100"
/>
))}
</div>
<button type="submit">Submit</button>
</form>
</div>
);
};
export default Page;
pages/api/upload.ts
import type { NextApiRequest, NextApiResponse } from 'next';
export default function handler(req: NextApiRequest, res: NextApiResponse) {
const images = req.body.images;
res.status(200).json('upload success');
}
Discussion