반응형
효과 캡처:
페이지 업로드
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
头像:<img id="avatar" src="" height="35" width="35" alt=""><br />
选择文件:<input type="file" id="file1" /><br />
<input type="button" id="upload" value="업로드" /> <span id="result"></span>
<img src="5fd411e985d2c939b90e2dfb.gif" height="100" width="100" style="display:none" id="imgWait" />
<script src="jquery-1.11.2.min.js"></script>
<script>
$(function () {
$("#upload").click(function () {
$("#imgWait").show();
var formData = new FormData();
formData.append("myfile", document.getElementById("file1").files[0]);
$.ajax({
url: "upload.php",
type: "POST",
dataType: 'json',
data: formData,
/**
*올바른 Content-Type은 false가 되어야 자동으로 추가됩니다,그렇지 않으면 error 단계를 수행합니다
*/
contentType: false,
/**
* formdata에 대한 jQuery의 기본 처리를 피하려면 false가 필요합니다,그렇지 않으면 Uncaught TypeError: Illegal invocation
* XMLHttpRequest가 formdata를 올바르게 처리함
*/
processData: false,
success: function (data) {
if(data.code == 200){
$('#avatar').attr('src',data.datas.filename);
}
$('#result').html(data.msg);
$("#imgWait").hide();
setTimeout(function(){
$('#result').html('');
}, 1200);
},
error: function () {
alert("업로드 실패!");
$("#imgWait").hide();
}
});
});
});
</script>
</body>
</html>
백그라운드 코드:
<?php
$tmp_name = $_FILES['myfile']['tmp_name'];
$current_time = date("Y-m-d H-i-s");
if(is_uploaded_file($tmp_name)){
$filename = './'.$current_time.'.jpg';
$return = move_uploaded_file($tmp_name,$filename);
$return ? output('200','업로드 성공!',['filename' => $filename]) : output('400','上传失败!');
}else{
output('555','불법 파일!');
}
function output($code,$msg,$datas = array()){
$outputData = array(
'code' => $code,
'msg' => $msg,
'datas' => $datas
);
exit(json_encode($outputData));
}
반응형
'개발 꿀팁 > PHP' 카테고리의 다른 글
맥 아래 PHP 개발 환경 구축 (0) | 2022.07.29 |
---|---|
PHP에서 잘 알려지지 않은 10개의 함수 (0) | 2022.07.29 |
PHP 클래스 라이브러리 PHPqrCode를 사용하여 QR코드 생성 (0) | 2022.07.29 |
맥 업그레이드 PHP 버전 (0) | 2022.07.28 |
Ajax+PHP 기반 단일 파일, 다중 파일 비동기 업로드 인스턴스 (0) | 2022.07.28 |