바닐라 ajax 파일업로드 예제
이번에 지인이 이미지(jpg, png, gif) 업로드를 꼭 아작스로 해야 된다고 "발광"을 떨기에 만들어 준 소스입니다.
파일명은 202312252103.jpg 식으로 업로드시의 년월일시분초로 이름이 만들어집니다.
그냥 다 프론트에서 만들고 넘겨서 실제 액션문은 너무 소박하네요.
상단의 오디오는 데이터를 주고 받으면서 스트리밍이 끊기나 아니나를 확인하기 위해 넣은 것이니 삭제해도 됩니다.
오류나 예외처리는 없습니다.ㅜㅠ 본인들이 알아서 넣어주세요.
----------
main.php
[code]
<audio src="https://blog.kakaocdn.net/dn/PmTxy/btsk27xopkC/smpoMRN8VNc0Fim0V05g91/tfile.mp3" controls></audio>
<form id="uploadForm" enctype="multipart/form-data" method="post">
<input type="file" name="upload_file" accept=".jpg,.png,.gif">
<input type="hidden" name="upload_file_name">
</form>
<button type="button" id="uploadButton" style="cursor:pointer">업로드</button>
<div id="ajaxDiv"></div>
<script>
actionUrl = "./upload.php";
uploadDirectory = "./";
function todayData() {
today = new Date();
mdhmsToday = ["Month", "Date", "Hours", "Minutes", "Seconds"];
ymdhmsToday = today.getFullYear();
for (i of mdhmsToday) ymdhmsToday += ("0" + (today["get" + i]() + (i == "Month" ? 1 : 0))).slice(-2);
return ymdhmsToday;
}
document.querySelector("#uploadForm").onchange = function() {
fileName = todayData();
fileExtension = this.querySelectorAll("input")[0].value.slice(-4).toLowerCase();
imageSrc = this.querySelectorAll("input")[1].value = uploadDirectory + fileName + fileExtension;
}
function ajaxUpload() {
uploadData = new FormData(document.querySelector("#uploadForm"));
ajax = new XMLHttpRequest();
ajax.open("post", actionUrl);
ajax.onload = () => {
document.querySelector("#ajaxDiv").innerHTML = "<img src='" + imageSrc + "'>";
}
ajax.send(uploadData);
}
document.querySelector("#uploadButton").onclick = ajaxUpload;
</script>
[/code]
----------
upload.php
[code]
<?php
move_uploaded_file($_FILES['upload_file']['tmp_name'], $_POST['upload_file_name']);
[/code]
게시판 목록
개발자팁
질문은 QA에서 해주시기 바랍니다.
| 번호 | 분류 | 제목 | 글쓴이 | 날짜 | 조회 |
|---|---|---|---|---|---|
| 5066 | 기타 |
DogFoot개발
|
4년 전 | 1819 | |
| 5065 | PHP |
DogFoot개발
|
4년 전 | 1529 | |
| 5064 | PHP |
happyl
|
4년 전 | 1918 | |
| 5063 | node.js |
DogFoot개발
|
4년 전 | 1675 | |
| 5062 | node.js |
DogFoot개발
|
4년 전 | 1693 | |
| 5061 | node.js |
DogFoot개발
|
4년 전 | 1416 | |
| 5060 | node.js |
DogFoot개발
|
4년 전 | 1254 | |
| 5059 | node.js |
DogFoot개발
|
4년 전 | 1250 | |
| 5058 | 기타 |
DogFoot개발
|
4년 전 | 2697 | |
| 5057 | 웹서버 |
DogFoot개발
|
4년 전 | 2726 | |
| 5056 | MySQL | 4년 전 | 1506 | ||
| 5055 | 기타 | 4년 전 | 1435 | ||
| 5054 | OS | 4년 전 | 2070 | ||
| 5053 | 웹서버 | 4년 전 | 3632 | ||
| 5052 | OS | 4년 전 | 2425 | ||
| 5051 | PHP | 4년 전 | 2189 | ||
| 5050 | 웹서버 | 4년 전 | 1722 | ||
| 5049 | MySQL | 4년 전 | 1899 | ||
| 5048 | OS | 4년 전 | 2704 | ||
| 5047 | PHP | 4년 전 | 4375 | ||
| 5046 | MySQL | 4년 전 | 1820 | ||
| 5045 | MySQL | 4년 전 | 1944 | ||
| 5044 | MySQL | 4년 전 | 4135 | ||
| 5043 | MySQL | 4년 전 | 1891 | ||
| 5042 | 기타 |
|
4년 전 | 2636 | |
| 5041 | MySQL | 4년 전 | 1998 | ||
| 5040 | MySQL | 4년 전 | 1726 | ||
| 5039 | MySQL | 4년 전 | 1500 | ||
| 5038 | MySQL | 4년 전 | 1336 | ||
| 5037 | OS | 4년 전 | 4432 |
댓글 작성
댓글을 작성하시려면 로그인이 필요합니다.
로그인하기