1.使用form表單的形式
第一種方式就是使用FormData的方式進(jìn)行上傳
html代碼:
<el-form :model="upform" :rules="uprules" style="width:100%;" ref="upform" label-width="100px">
<el-form-item label="上傳附件:">
<el-button type="primary"
@click="upLoad()"
size="mini"
class="form-btn"
>點(diǎn)擊上傳</el-button>
</el-form-item>
</el-form>
JS代碼:
// 請(qǐng)求-上傳附件
upLoad() {
const _this = this;
// const fileType = [
// "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
// "application/vnd.ms-excel"
// ];
const fileType = ['xls','xlsx','et']
const inputFile = document.createElement("input")
inputFile.type = "file"
inputFile.style.display = "none"
document.body.appendChild(inputFile)
inputFile.click()
inputFile.addEventListener("change",function() {
const file = inputFile.files[0];
var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
if (!fileType.includes(testmsg)) {
_this.$message.warning("上傳的文件格式只能是,xls,xlsx,et");
document.body.removeChild(inputFile);
return false;
}
const formData = new FormData();
formData.append("file", file);
window.request({
url:'xxx/xxx',
data:formData,
success:(res)=> {
if (res.code === 200) {
_this.$message.success(res.message || "導(dǎo)入成功");
_this.getTableList();
}else {
_this.$message.success("導(dǎo)入失敗");
},
finally:()=> {
document.body.removeChild(inputFile);
})
})
},
2.使用element-ui的el-upload的方式進(jìn)行上傳文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-680601.html
這里我是根據(jù)需求封裝了一個(gè)組件文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-680601.html
<template>
<div id="uploadFile">
<el-form-item :label="uploadParams.label" :label-width="uploadParams.labelWidth" :id="uploadParams.key">
<el-upload
:data="paramsData"
:ref="uploadParams.key"
class="upload-demo"
:before-upload="beforeUploadFile"
:action="actionUrl"
:on-preview="handlePreview"
:on-success="handleSuccess"
:on-error="handleError"
:before-remove="beforeRemove"
:on-remove="handleRemove"
:disabled="uploadParams.disabled?uploadParams.disabled: false"
:limit="uploadParams.limit?uploadParams.limit:1"
:on-exceed="handleExceed"
:file-list="uploadParams.fileList">
<el-button size="small" :disabled="uploadParams.disabled?uploadParams.disabled: false" type="primary">點(diǎn)擊上傳</el-button>
<div v-if="uploadParams.showTip?uploadParams.showTip: false" slot="tip" class="el-upload__tip" style="word-break:break-all;"> {{`只能上傳${uploadParams.type}文件,且不超過(guò)${uploadParams.fileSize}M`}} </div>
<div v-if="uploadParams.showTip2?uploadParams.showTip2: false" slot="tip" class="el-upload__tip" style="word-break:break-all;color:red"> {{`只能上傳${uploadParams.limit}個(gè)${uploadParams.type}文件,再次上傳需要?jiǎng)h除之前的模板`}} </div>
</el-upload>
</el-form-item>
</div>
</template>
<script>
// ===============上傳文件組件使用=================
// =========嵌套在el-form中調(diào)用組件: <el-from> <uploadFile :uploadParams="傳遞參數(shù)" @getFileIdReturn="接受上傳文件id數(shù)組回傳"></uploadFile> </el-form>
// ========= uploadParams中參數(shù)說(shuō)明: label: form的label,labelWidth: form的label-width, key: 指定的組件標(biāo)識(shí),
// ================================ fileList: 存放文件數(shù)組,limit:存放限制上傳數(shù)量,
// ================================ type: 附件類型(.xxx),多種以英文逗號(hào)分隔, fileSize: 附件大小(M為單位)
// ================================ , showTip: 是否展示提示信息
//
import fileAPI from "@/api/fileApi";
import Config from "@/settings";
export default {
name: "uploadFile",
props: {
uploadParams: Object,
paramsData:Object
},
data() {
return {
fileIdList: [],//存放附件id數(shù)組
actionUrl: process.env.VUE_APP_BASE_API + "xxxx/xxxx",//文件上傳地址
removeUrl: 'xxxx/xxx',// 刪除文件地址
}
},
created() {},
methods: {
// 文件上傳成功時(shí)的鉤子
handleSuccess(res, file, fileList) {
this.$message.success("文件上傳成功");
let filename = fileList.map(item => {
return item.name;
});
this.fileIdList.push(res.data.fid);
this.$emit("getFileIdReturn", this.fileIdList);//返回文件id數(shù)組
},
// 文件上傳失敗時(shí)的鉤子
handleError() {
this.$message.error("文件上傳失敗");
},
handleExceed(files, fileList) {
//上傳超過(guò)限制個(gè)數(shù)
this.$message.warning(`當(dāng)前限制選擇 ${this.uploadParams.limit} 個(gè)文件,本次選擇了 ${ files.length } 個(gè)文件,
共選擇了 ${files.length + fileList.length} 個(gè)文件`
);
},
beforeRemove(file, fileList) {
if(file.url==undefined){
return;
}
// 移除前鉤子
return this.$confirm(`確定移除 ${file.name}?`)
},
// 上傳文件之前的鉤子, 參數(shù)為上傳的文件,若返回 false 或者返回 Promise 且被 reject,則停止上傳
beforeUploadFile(file) {
console.log('before upload')
// console.log(file)
const extension = file.name.substr(file.name.lastIndexOf('.') + 1);
console.log('extension', extension)
const size = file.size / 1024 / 1024;
let temp = this.uploadParams.type.split(",");
let typeArr = [];
temp.forEach(element => {
typeArr.push(element.substr(element.lastIndexOf('.') + 1));
});
if (!(typeArr.includes(extension)) ) {
this.$message.warning(`只能上傳后綴是${this.uploadParams.type}的文件`)
return false
}
if (size > this.uploadParams.fileSize) {
this.$message.warning(`文件大小不得超過(guò)${this.uploadParams.fileSize}M`)
return false
}
return extension && size
},
handleRemove(file, fileList) {
// 移除附件時(shí)鉤子
console.log(file);
let id;
if(file.url) {
id = file.url.split("id=")[1];
}else if(file.response) {
id = file.response.data.fid;
}else {
this.uploadParams.fileList = fileList;
return
}
window.request({
url: this.removeUrl,
data: {
ids: id
},
success: (res) => {
if(res.code === 200) {
this.$message.success("刪除成功!");
this.uploadParams.fileList = fileList;
this.fileIdList.forEach((element, index) =>{
if(element == id) {
this.fileIdList.splice(index, 1);
}
});
this.handLoadingShow(false)
this.$emit("getFileIdReturn", this.fileIdList);//返回文件id數(shù)組
}
}
})
},
handlePreview(file) {
//點(diǎn)擊文件列表中已上傳的文件時(shí)的鉤子
console.log(file);
let fileurl;
if(file.url) {
fileurl = Config.downUrl + file.url;
}else {
fileurl = Config.downUrl + process.env.VUE_APP_BASE_API + "xxx/下載地址" + file.response.data.fid;
}
window.location.href = fileurl;
},
// 上傳控件的回顯====回顯加載時(shí)使用
loadFileList (urlAndFid) {//參數(shù)url加文件
let templateList = null;
const downloadUrl = process.env.VUE_APP_BASE_API + xxx/xxx";
this.uploadParams.fileList = [];
this.fileIdList = [];
window.request({
url: urlAndFid,
success: ({ data }) => {
templateList = data;
templateList.forEach((element, index) => {
const obj = {};
obj.name = templateList[index].name;
obj.url = downloadUrl + templateList[index].id;
obj.id = templateList[index].id;
this.uploadParams.fileList.push(obj);
this.fileIdList.push(obj.id);
});
this.$emit("getFileIdReturn", this.fileIdList);//返回文件id數(shù)組
}
});
},
loadFileList2 (fileUrl, fileParam) {//url: fileUrl,參數(shù)fileParam
let templateList = null;
const downloadUrl = process.env.VUE_APP_BASE_API + "xxx/xxx";
this.uploadParams.fileList = [];
this.fileIdList = [];
window.request({
url: fileUrl,
data: fileParam,
success: ({ data }) => {
templateList = data;
templateList.forEach((element, index) => {
const obj = {};
obj.name = templateList[index].name;
obj.url = downloadUrl + templateList[index].id;
obj.id = templateList[index].id;
this.uploadParams.fileList.push(obj);
this.fileIdList.push(obj.id);
});
this.$emit("getFileIdReturn", this.fileIdList);//返回文件id數(shù)組
}
});
},
}
}
</script>
到了這里,關(guān)于vue前端實(shí)現(xiàn)上傳文件的兩種方式的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!