React의 server에 img를 업로드하고 그 이미지를 받아오기 위하여
[client]
const [formData,setFormData]= useState({e_title: "",e_img: ""})
const onChange=(e)=>{
const {name,value}= e.target;
setFormData({...formData, [name]:value})
}
2️⃣ 1의 input에서 파일을 onChange하면 upload 경로로 post 전송
// 타입이 file인 input이 onChange 되었을 때 호출되는 함수
// 변경된 file을 서버로 업로드
❗
const onChangeImage=(e:React.ChangeEvent<HTMLInputElement>)=>{
const imageFormData= new FormData();
imageFormData.append(e.target.name, e.target.files![0]);
axios.post(`${API_URL}/upload`,imageFormData,{
headers:{'content-type':'multipart/form-data'}
}).then(res=>{
setFormdata({...formdata, b_img: res.data.imageUrl})
}).catch(e=>alert(e))
}
const onSubmit=(e)=>{e.preventDefault(); addEvent();}
const addEvent=()=>{
axios.post(`${API_URL}/event`,formData)
.then(res=>{alert("등록되었습니다.")})
.catch(e=>{alert(e)})
}
return (
<form onSubmit={onSubmit}><table><tbody>
<tr>
<td>제목</td>
<td>
<input type='text' name='e_title'
value={formData.e_title} onChange={onChange}/>
</td>
</tr>
1️⃣ form 구문내에서 img를 받아오기 위해서 input 작성 및 input의 name을 file로, onChange를 onChangeImage로 지정
<tr>
<td>이미지1</td>
<td>
<input type="file" name='file' onChange={onChangeImage}/>
{
formData.e_img1 &&
<div>
<img src={`${API_URL}/upload/event/${formData.e_img}`}
width="100px" alt=''/>
</div>
}
</td>
</tr>
<tr>
<td> <button></button></td>
</tr>
</tbody></table></form>
);
};
[server]
1️⃣ img등록을 위하여 multer 사용을 지정해 놓는다.
위의 client에서 onChangeImage함수가 실행되었을 때마다 res.send를 해줄 것이다.
const multer= require("multer"); // 이미지 등록을 위하여 사용!
app.use("/upload",express.static("upload"));
// upload 객체 생성
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'upload/'); // ❗ 여기서 upload/는 파일을 저장할 장소로, 만들어져 있는 폴더이다.
},
filename: (req,file,cb)=>{
const newFilename = file.originalname;
cb(null, newFilename);
}
})
// storage 생성
const upload= multer({storage:storage});
// upload 경로로 post요청이 왔을때
app.post("/upload",upload.single('file'),(req,res)=>{
res.send({imageUrl: req.file.filename})
})
2️⃣ 위의 client에서 addEvent함수가 실행되었을 때 쿼리문을 실행할 것이다.
3️⃣ 전송 응답을 받아서 DB에 e_img:"응답결과"를 입력함
app.post('/event', async (req,res)=>{
const {e_title, e_img}= req.body;
conn.query(`insert into event(e_title, e_img) values (?,?)`,
[e_title, e_img],(err,result,fie)=>{if(!result){console.log(err);}}
)
})