Last active
September 3, 2021 08:10
-
-
Save ktmihs/9d9a0db4a63cdeb93eb61ceea1d2c91f to your computer and use it in GitHub Desktop.
[node.js/Koa][React] 이미지 업로드
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Router from 'koa-router' | |
import Image from '../../models/image' | |
import multer from '@koa/multer' | |
const images = new Router() | |
// 파일을 저장할 디렉토리 설정 | |
const upload = multer({ | |
dest: __dirname+'/images/' // 이미지 업로드 경로(folder 새로 만듦) | |
}) | |
images.post('/image', upload.single('image'), // formdata에 image로 저장된 file 하나(single)를 저장(upload에 지정한 경로) | |
async(ctx) => { // DB 저장 | |
console.log(ctx.request.body) // body에는 post로 받아온 image data 있음 (body가 비어있다면 제대로 전달 안 온 것) | |
const { filename,hospitalname } = ctx.request.body // formdata 안에 추가한 항목 | |
const image=new Image({ filename,hospitalname }) | |
try{ | |
await image.save() | |
} catch(e){ | |
return ctx.throw(200,e) | |
} | |
ctx.body = image | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React,{useState} from 'react' | |
... | |
function imageUpload(){ | |
const formData=new FormData() | |
// FormData에 data추가는 append(key, value)로 넣어줌 | |
const [image,setImage]=useState('') | |
const [form,setForm]=useState(new FormData) | |
const config = { // server로 보내줄 config 미리 작성 | |
headers: { | |
'content-type': 'multipart/form-data' | |
} | |
} | |
const handleImage=(e)=>{ // e.target.files[0]은 선택된 첫 번째 파일을 의미 | |
setImage(e.target.value) | |
formData.append('image', e.target.files[0]) // server에서 image로 찾음 | |
formData.append('filename',e.target.files[0].name) // 파일명 | |
// formData.append('hospitalname',name) // 이후 식별을 위한 병원명 추가 | |
setForm(formData) | |
} | |
const handleSubmit=()=>{ | |
axios.post("/api/images/image",form,config) // formData는 content type을 작성해줘야 함 | |
.then((response) => { | |
for(let data of formData){console.log(data[0],data[1])} // formData console에 찍는 방법 | |
}) | |
.catch((error) => { | |
console.log(error) | |
}) | |
} | |
return( | |
<form onSubmit={handleSubmit}> | |
<input type="file" value={image} accept="image/*" name="image" onChange={handleImage} /> | |
</form> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment