原生JavaScript+PHP多圖上傳實(shí)現(xiàn)示例
摘要
很多場(chǎng)景下需要選擇多張圖片上傳,或者是批量上傳以提高效率,多圖上傳的需求自然就比較多了,本文使用最簡(jiǎn)單的XMLHttpRequest異步上傳圖片。
界面

上傳示例

index.html
<!DOCTYPE html>
<html>
<head>
<title>多圖上傳</title>
<meta charset="utf-8">
<style>
#fileInput{
width: 500px;
height: 45px;
margin: 50px auto 0;
background: #eee;
display: block;
padding: 20px 20px;
border-radius: 20px;
}
#previewContainer{
width: 500px;
margin: 10px auto;
background: #eee;
padding: 20px 20px;
display: none;
}
.preview-image {
max-width: 200px;
max-height: 200px;
margin-bottom: 10px;
}
</style>
</head>
<body>
<!--選擇文件-->
<input type="file" id="fileInput" accept="image/*" multiple>
<div id="previewContainer"></div>
<script>
const fileInput = document.getElementById('fileInput');
const previewContainer = document.getElementById('previewContainer');
// 監(jiān)聽(tīng)選擇文件
fileInput.addEventListener('change', handleFileSelect);
function handleFileSelect(event) {
const files = event.target.files;
for (let i = 0; i < files.length; i++) {
const file = files[i];
const reader = new FileReader();
reader.onload = function(event) {
const image = document.createElement('img');
image.className = 'preview-image';
image.src = event.target.result;
previewContainer.appendChild(image);
// 將文件上傳至服務(wù)器
uploadImage(file);
}
reader.readAsDataURL(file);
}
}
// 將文件上傳至服務(wù)器
function uploadImage(file) {
const xhr = new XMLHttpRequest();
const formData = new FormData();
// 將文件添加到formData對(duì)象
formData.append('image', file);
// 設(shè)置XHR請(qǐng)求的處理函數(shù)
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
console.log('上傳成功');
// 顯示圖片預(yù)覽區(qū)域
document.querySelector('#previewContainer').setAttribute('style', 'display:block');
// 打印JSON
console.log(JSON.parse(xhr.response))
} else {
console.log('上傳失敗');
}
}
}
// 發(fā)送POST請(qǐng)求到服務(wù)器
xhr.open('POST', 'upload.php', true);
xhr.send(formData);
}
</script>
</body>
</html>upload.php
(請(qǐng)建立一個(gè)upload文件夾以存放上傳的文件)
<?php
// 編碼
header("Content-type:application/json");
// 檢查是否有文件上傳
if (isset($_FILES['image'])) {
// 獲取上傳的文件信息
$file = $_FILES['image'];
// 獲取文件名
$fileName = $file['name'];
// 獲取文件的臨時(shí)路徑
$tmpFilePath = $file['tmp_name'];
// 指定保存目錄
$uploadDir = 'upload/';
// 驗(yàn)證是否為圖片文件
if ((($_FILES["image"]["type"] == "image/gif")
|| ($_FILES["image"]["type"] == "image/jpeg")
|| ($_FILES["image"]["type"] == "image/jpg")
|| ($_FILES["image"]["type"] == "image/pjpeg")
|| ($_FILES["image"]["type"] == "image/x-png")
|| ($_FILES["image"]["type"] == "image/png"))
&& ($_FILES["image"]["size"] < 10485760)){
// 生成唯一的文件名
$uniqueFileName = uniqid() . '_' . $fileName;
// 拼接保存路徑
$uploadPath = $uploadDir . $uniqueFileName;
// 獲取HTTP協(xié)議
function get_http_type(){
$http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
return $http_type;
}
// 將臨時(shí)文件移動(dòng)到目標(biāo)路徑
if (move_uploaded_file($tmpFilePath, $uploadPath)) {
// 上傳成功
// 可以在此處進(jìn)行進(jìn)一步處理,比如生成縮略圖、添加水印等
$result = array(
'code' => 200,
'msg' => '上傳成功',
'url' => get_http_type().dirname($_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']).'/'.$uploadPath
);
} else {
// 上傳失敗
$result = array(
'code' => 202,
'msg' => '文件上傳失敗'
);
}
}else{
// 不合規(guī)的文件
$result = array(
'code' => 202,
'msg' => '不合規(guī)的文件'
);
}
} else {
// 沒(méi)有文件上傳
$result = array(
'code' => 202,
'msg' => '沒(méi)有選擇要上傳的文件'
);
}
// JSON
echo json_encode($result, JSON_UNESCAPED_UNICODE);
?>以上就是原生JavaScript+PHP多圖上傳實(shí)現(xiàn)示例的詳細(xì)內(nèi)容,更多關(guān)于原生JavaScript PHP多圖上傳的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
PHP基于cookie實(shí)現(xiàn)統(tǒng)計(jì)在線人數(shù)功能示例
這篇文章主要介紹了PHP基于cookie實(shí)現(xiàn)統(tǒng)計(jì)在線人數(shù)功能,涉及php文件讀寫(xiě)、cookie訪問(wèn)、計(jì)算等相關(guān)操作技巧,需要的朋友可以參考下2019-01-01
使用bcompiler對(duì)PHP文件進(jìn)行加密的代碼
在網(wǎng)上無(wú)意間看到這個(gè)功能代碼,還沒(méi)有去試,以后有機(jī)會(huì)用到時(shí)在試一試。收藏一下。2010-08-08
PHP函數(shù)checkdnsrr用法詳解(Windows平臺(tái)用法)
這篇文章主要介紹了PHP函數(shù)checkdnsrr用法,分析講解了在Windows平臺(tái)使用checkdnsrr函數(shù)的方法,需要的朋友可以參考下2016-03-03
php相當(dāng)簡(jiǎn)單的分頁(yè)類(lèi)
代碼比較簡(jiǎn)單,學(xué)習(xí)php類(lèi)的朋友,可以看下2008-10-10
PHP輸出XML格式數(shù)據(jù)的方法總結(jié)
這篇文章主要介紹了PHP輸出XML格式數(shù)據(jù)的方法,結(jié)合實(shí)例形式總結(jié)分析了php常用的xml格式數(shù)據(jù)輸出相關(guān)操作技巧,需要的朋友可以參考下2017-02-02

