本文共 3490 字,大约阅读时间需要 11 分钟。
<template> <div> <el-card> <h1>轮播图 - 图片上传管理</h1> <el-divider></el-divider> <!--注意:使用 :model="uploadImgForm" 不要使用 v-model="uploadImgForm"--> <el-form ref="formRef" :model="uploadImgForm"> <el-form-item label="" prop="productImg"> <!-- action : 上传的地址 --> <!-- on-preview: 点击图片时的回调 --> <!-- on-remove: 删除图片后的回调 --> <el-upload ref="upload" action="/smoke_product/xxxxxxxxxx :auto-upload="false" list-type="picture-card" :on-preview="handlePreview" :on-remove="handleRemove" :on-change="uploadImage" :file-list="showFiles" > <i class="el-icon-plus"></i> </el-upload> <!-- 预览图片 --> <el-dialog :visible.sync="dialogVisible" size="tiny"> <img width="100%" :src="dialogImageUrl" alt /> </el-dialog> </el-form-item> </el-form> <div class="dialog-footer"> <el-button type="primary" @click="submitForm()">上传</el-button> <el-button @click="dialogFormVisible = false">取 消</el-button> </div> </el-card> </div></template><script>import { uploadLoopImage } from "../../api/equipment";export default { data() { return { dialogImageUrl: "", dialogVisible: false, uploadImgForm: { productImg: "", }, file: [], // 上传图片时,改变存放改变列表里面的图片数组 showFiles: [], // 存放图片的数组 newFiles: [], // 存放最新图片的数组 }; }, methods: { // 删除图片 handleRemove(file, fileList) { console.log(file, fileList); }, // 点击图片 handlePreview(file) { // console.log("file", file); this.dialogImageUrl = file.url; this.dialogVisible = true; }, // 上传图片 uploadImage(file, fileList) { this.file = fileList; //主要用于接收存放所有的图片信息 //限制上传文件为2M let sizeIsSatisfy = file.size < 2 * 1024 * 1024 ? true : false; if (sizeIsSatisfy) { return true; } else { this.fileSizeIsSatisfy = true; return false; } }, //提交form表单 submitForm() { this.$refs.formRef.validate((valid) => { if (valid) { if (this.file.length <= 0) { this.$message.error("请至少上传一个文件!"); return; } if (this.fileSizeIsSatisfy) { this.$message.error("上传失败!存在文件大小超过2M!"); return; } this.processFile(); //处理files的数据变成键值对的形式 返回newFiles这个数组 console.log(this.newFiles); var param = new FormData(); // FormData 对象 this.newFiles.forEach((fileItem) => { console.log(fileItem.imgFile); var list = fileItem; var file = list.imgFile; /** * 注意: * "file" 这个名字一定要和 后台的一样 */ param.append("file", file); // 文件对象 }); // console.log(param) uploadLoopImage(param).then( (res) => { console.log(res); // 上传成功的 图片地址 }, (error) => { console.log(error); } ); } else { console.log("error submit!!"); return false; } }); }, //全部的图片添加到 newFiles中 processFile() { this.file.forEach((item) => { let objFile = {}; objFile.title = "file"; objFile.imgFile = item.raw; this.newFiles.push(objFile); }); }, },};</script><style lang="scss" scoped>.el-card { margin-top: 10px;}.el-form { margin-top: 10px;}</style>
转载地址:http://aqir.baihongyu.com/