這邊博文主要介紹的是使用element-ui的upload上傳組件實現自定義多圖上傳的方式。
element-ui的upload上傳組件,如果是多圖上傳,實際上在請求中爲單個文件上傳,只是提交方法中自循環,直至上傳文件列表爲空爲止。
不多說上代碼:
HTML:
<el-upload class="upload-demo" action="http://localhost:80" :limit='5' :auto-upload="false" :on-exceed='uploadOverrun' ref="upload" :http-request='submitUpload' :on-change='changeUpload'>
<el-button size="small" type="primary">點擊上傳</el-button>
<div slot="tip" class="el-upload__tip">只能上傳jpg/png文件,且不超過500kb</div>
</el-upload>
<el-button @click = 'submitAssess'>提交到服務器</el-button>
JS:
uploadOverrun: function() {
this.$message({
type: 'error',
message: '上傳文件個數超出限制!最多上傳5張圖片!'
});
},
changeUpload: function(file, fileList) {//預覽圖片
this.fileList = fileList;
this.$nextTick(
() => {
let upload_list_li = document.getElementsByClassName('el-upload-list')[0].children;
for (let i = 0; i < upload_list_li.length; i++) {
let li_a = upload_list_li[i].children[0];
let imgElement = document.createElement("img");
imgElement.setAttribute('src', fileList[i].url);
imgElement.setAttribute('style', "max-width:50%;padding-left:25%");
if (li_a.lastElementChild.nodeName !== 'IMG') {
li_a.appendChild(imgElement);
}
}
})
},
submitUpload: function(content) {//自定義的上傳圖片的方法
//1. 創建formData 利用AXIOS傳遞
let formData = new FormData;
formData.append('file', content.file);
let config = {
'Content-Type': 'multipart/form-data'
}
let var_this = this;
axios.post('/Index/upload', formData, config)
.then(function(response) {
if (!response.data.success) {
var_this.$message({
message: response.data.message,
type: 'error'
});
}
})
.catch(function(error) {
console.log(error);
})
},
submitAssess: function() {this.$refs.upload.submit(); //調用submit方法
//其他業務代碼。
}
php
public function upload(){
//上傳文件
if(!empty($_FILES)) {
if(!empty($_SESSION)){
//拼接路徑
$filePathArr = explode('/', $_SERVER['SCRIPT_FILENAME']);
array_pop($filePathArr);
$filePath = implode('/', $filePathArr);
$filePath .= '/static/upload/';
if(!is_dir($filePath)){ //創建文件夾
mkdir($filePath);
}
$filePath .= Session::get('user').'-->'.md5(time()).$_FILES['file']['name'];
if(move_uploaded_file($_FILES["file"]["tmp_name"],$filePath)){
$filePath = str_replace($_SERVER['CONTEXT_DOCUMENT_ROOT'],"",$filePath);
//其他業務代碼.我在製作此處時,我先將圖片存入數據庫
}else{
$data = returnData(false,'對不起,操作失敗!請稍候再試!');
}
}else{
$data = returnData(false,'請登錄後再試!');
}
echo json_encode($data);
}
}