vue+element_ui上传文件,并传递额外参数操作
(编辑:jimmy 日期: 2024/12/23 浏览:3 次 )
需求:
1、文件大小验证
2、文件类型验证
3、额外参数传输
<template> <el-upload class="upload-demo" action :limit="1" :file-list="formFileList" :http-request="handleUploadForm" :on-exceed="formHandleExceed" :on-remove="formHandleRemove" :before-upload="beforeUploadForm" accept=".csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"> <el-button type="primary">上传文件</el-button> <span slot="tip" class="el-upload__tip" style="margin: 0 10px;">只能上传xlsx/xls/csv文件,且不超过{{formMaxSize}}M</span> </el-upload> </template> <script> export default { data () { return { formMaxSize: 10, // 上传文件大小 formFileList: [], // 显示上传文件 uploadFormFileList: [] // 确定上传文件 } }, methods: { // 开始上传前验证 beforeUploadForm (file) { // 验证文件大小 if (file.size / 1024 / 1024 > this.formMaxSize) { this.$message({ message: `上传文件大小不能超过${this.formMaxSize}M!`, type: 'warning' }) return false } // 中文乱码处理 if (file.raw) { let reader = new FileReader() // 读取文件内容 reader.readAsText(file.raw, 'gb2312') // 防止中文乱码问题,不加reader.onload方法都不会触发 reader.onload = function (e) { this.contentHtml = e.target.result // txt文本内容,接下来就可以对其进行校验处理了 } } // 验证文件类型 var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1) const extension = testmsg === 'xlsx' || testmsg === 'xls' || testmsg === 'csv' if (!extension) { this.$message({ message: '上传文件只能是xlsx/xls/csv格式!', type: 'warning' }) } return extension }, // 移除上传列表中文件 formHandleRemove (file, formFileList) { let thiz = this for (let i = 0; i < thiz.uploadFormFileList.length; i++) { if (thiz.uploadFormFileList[i].pname === file.name) { thiz.uploadFormFileList.splice(i, 1) break } } }, // 允许上传文件个数验证 formHandleExceed (files, formFileList) { this.$message.warning(`当前限制选择 1 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + formFileList.length} 个文件`) }, // 上传文件 handleUploadForm (param) { let thiz = this let formData = new FormData() formData.append('uid', '上传文件编号') // 额外参数 formData.append('files', param.file) let loading = thiz.$loading({ lock: true, text: '上传中,请稍候...', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)' }) thiz.$axios.post('http://localhost:8080/upload/file', formData).then(({data}) => { if (data.statusCode === 233) { thiz.$message('上传文件成功,' + data.message) thiz.formFileList = [] thiz.uploadFormFileList = [] } else { thiz.formFileList = [] thiz.uploadFormFileList = [] thiz.$message('上传文件失败,' + data.message) } loading.close() }) } } } </script> <style lang="scss" scoped> </style>
总结:
关于el-upload中各属性的配置,可以看element_ui官网
后端接受上传文件和额外参数:
@RequestParam(value = "uid") String uid, @RequestParam(value = "files") MultipartFile[] files
补充知识:vue利用elementUI上传文件以及其他参数的处理方式
将文件自动上传改为false
:auto-upload="false"
点击保存的时候,调用el-upload的上传方法
代码如下(封装的上传方法)
export function mpp(data) { return new Promise(function(resolve, reject) { let data = { method: "POST", url:url, data:data } resolve(axios(data)); }) } <template>
<!--导入计划 --> <div class="associationPlan"> <el-form :model="dataModel" :rules="rules" ref="associationPlan" label-width="100px"> <el-form-item label="项目名称:" prop="projectArry"> <el-cascader :options="listOrgInfoList" v-model="dataModel.projectArry" :props="defaultProp" size="small" placeholder="请选择项目" style="width:100%;" clearable :disabled="isCompany"></el-cascader> </el-form-item> <el-form-item label="计划级别:" prop="level"> <el-select size="small" v-model="dataModel.level" placeholder="请选择:" clearable style="width:100%;"> <el-option v-for="(item,index) in planTypeList" :label="item.name" :value="item.number" :key="index"></el-option> </el-select> <span class="warnInfo" v-if="dataModel.level==1">一级进度计划匹配项目总工期,项目下只可建立一个,请确认后再添加!</span> </el-form-item> <el-form-item label="计划名称:" prop="name"> <el-input v-model.number="dataModel.name" size="small"></el-input> </el-form-item> <el-form-item label="导入计划:"> <el-upload accept=".mpp" style="display:inline-block;vertical-align: top;" ref="uploadAdd" action="" :auto-upload="false" :http-request="uploadImg" :on-success="uploadImgSuccess" :on-remove="handleRemove"> <el-button size="small" type="success">请选择文件</el-button> </el-upload> </el-form-item> </el-form> <div class="clickBtn"> <el-button @click="close" size="small">取消</el-button> <el-button @click="commit" size="small" type="primary">保存</el-button> </div> </div> </template>
<script> import { mapState, mapActions } from 'vuex'; import { plan,mpp} from "../api/system_interface.js"; export default { name: "associationPlan", data() { return { dataModel: { projectId: '', projectArry:[], level:null, name:'', parentId:'0' }, defaultProp: { children: "child", label: "name", value: "id" }, //数据校验 rules: { projectArry: [{ required: true, message: "请选择项目", trigger: "blur" }], name: [{ required: true, message: "请输入计划名称", trigger: "blur" }], level: [{ required: true, message: "请选择计划级别", trigger: "change" }] }, file:false, isCompany:false }; }, computed: { ...mapState([ 'listOrgInfoList', 'planTypeList' ]), }, methods: { ...mapActions([ 'getlistOrgInfoList' ]), update(){ let companyTypes = sessionStorage.getItem("companyType"); this.isCompany = companyTypes == 4"selectArry")); }, uploadImg (f) { // if(!f){ // this.$message.error("请上传文件!"); // return // } this.dataModel.projectId = this.dataModel.projectArry[this.dataModel.projectArry.length - 1]; let param = new FormData(); //创建form对象 param.append('file',f.file);//通过append向form对象添加数据 param.append('level',this.dataModel.level);//添加form表单中其他数据 param.append('projectId',this.dataModel.projectId);//添加form表单中其他数据 param.append('planName',this.dataModel.name);//添加form表单中其他数据 mpp(param)//上传 .then(response=>{ if(response.code == "200"){ this.$message.success("上传成功!"); this.close(); this.$emit("refreshData"); onSuccess(response.data); } }) .catch(({err}) => { f.onError() }) }, uploadImgSuccess(response, file, fileList) { // 缓存接口调用所需的文件路径 console.log('文件上传成功') // this.$message.success("上传成功!"); }, handleRemove(file, fileList) { // 更新缓存文件 console.log('文件删除') }, //重置方法 reset() { const associationPlan = this.$refs["associationPlan"]; associationPlan.resetFields(); this.dataModel.projectId = null; this.dataModel.name = ''; this.dataModel.level = ''; this.dataModel.projectArry = []; }, //关闭弹框 close() { this.$emit("close"); this.reset(); }, //点击提交 commit() { this.$refs["associationPlan"].validate(valid => { if (!valid) { return; } this.$refs.uploadAdd.submit(); // this.dataModel.projectId = this.dataModel.projectArry[this.dataModel.projectArry.length - 1]; // plan(this.dataModel) // .then(response => { // if (response.code == "200") { // this.$message.success("添加成功!"); // this.close(); // this.$emit("refreshData"); // } else { // this.$message.error(response.msg); // } // }) // .catch(error => { // }); }); }, } };
</script> <style lang="scss" scoped> .clickBtn { text-align: center; } .warnInfo{ // color: #feba51; color: rgb(64, 158, 255); } </style>
以上这篇vue+element_ui上传文件,并传递额外参数操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
下一篇:JavaScript实现浏览器网页自动滚动并点击的示例代码