✏️ HTML From
- javaScript 를 사용해 submit 을 가로채 fetch 방식의 rest api 로 요청을 보내는 방식으로 구현했다.
- form 태그의
enctype
속성엔 파일 업로드를 할 수 있는 컨텐츠 타입인 multipart/form-data
을 입력해주면 된다.
<div id="vacationContainer">
<h2>Vacation Photo Contest</h2>
<form class="form-horizontal" role="form"
enctype="multipart/form-data" id="vacationForm">
<div class="form-group">
<label for="fieldName" class="col-sm-2 control-label">Name</label>
<div class="col-sm-4">
<input type="text" class="form-control"
id="fieldName" name="name">
</div>
</div>
<div class="form-group">
<label for="fieldEmail" class="col-sm-2 control-label">Email</label>
<div class="col-sm-4">
<input type="email" class="form-control" required
id="fieldName" name="email">
</div>
</div>
<div class="form-group">
<label for="fieldPhoto" class="col-sm-2 control-label">Vacation photo</label>
<div class="col-sm-4">
<span class="btn btn-default btn-file">
Upload
<input type="file" class="form-control" required accept="image/*"
id="fieldPhoto" data-url="/upload" multiple name="photo">
</span>
<div id="fileUploads"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-4">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
</div>
- 아래는 api 요청을 보내고 응답에 따라 페이지를 동적으로 수정하는 javaScript 태그다.
<script>
document.getElementById('vacationForm')
.addEventListener('submit', evt => {
evt.preventDefault()
const body = new FormData(evt.target)
const container = document.getElementById('vacationContainer')
const url = '/api/vacation/{{year}}/{{month}}'
fetch(url, { method: 'post', body })
.then(resp => {
if(resp.status < 200 || resp.status >= 300)
throw new Error(`Request failed with status ${resp.status}`)
return resp.json()
})
.then(json => {
container.innerHTML = '<b>Thank you for submitting your photo!<b>'
})
.catch(err => {
container.innerHTML = `<b>We're sorry, we had a problem` +
`signing you up. Plass <a href="/newsletter">try again</a>` +
`<p>Error = ${err}</p>`
})
})
</script>
✏️ API 구현
📍 멀티파트 폼 처리 모듈 설치
npm i multiparty
📍 모듈 조립
const multiparty = require('multiparty')