上一篇 Vue +Element UI +vue-quill-editor 富文本编辑器及插入图片自定义 主要是写了富文本编辑器的自定义及编辑器中图片的上传并插入到编辑内容,这篇文章单独介绍一下element UI 图片上传控件的使用。首先要安装element并中引入,安装引入过程这里不再赘述。
1.引用element 上传控件。
<el-upload action="/mgr/common/imgUpload"//这里需要配置一下文件上传地址(跨域) list-type="picture-card" accept="image/*" :limit="imgLimit" :file-list="productImgs" :multiple="isMultiple" :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :on-exceed="handleExceed" :on-error="imgUploadError"> <i class="el-icon-plus"></i> </el-upload> <el-dialog :visible.sync="dialogVisible"> <img width="100%" :src="dialogImageUrl" alt=""> </el-dialog>
2.js
export default { data() { return { dialogImageUrl: '', dialogVisible: false, productImgs: [], isMultiple: true, imgLimit: 6 } }, methods: { handleRemove(file, fileList) {//移除图片 console.log(file, fileList); }, handlePictureCardPreview(file) {//预览图片时调用 console.log(file); this.dialogImageUrl = file.url; this.dialogVisible = true; }, beforeAvatarUpload(file) {//文件上传之前调用做一些拦截限制 console.log(file); const isJPG = true; // const isJPG = file.type === 'image/jpeg'; const isLt2M = file.size / 1024 / 1024 < 2; // if (!isJPG) { // this.$message.error('上传头像图片只能是 JPG 格式!'); // } if (!isLt2M) { this.$message.error('上传图片大小不能超过 2MB!'); } return isJPG && isLt2M; }, handleAvatarSuccess(res, file) {//图片上传成功 console.log(res); console.log(file); this.imageUrl = URL.createObjectURL(file.raw); }, handleExceed(files, fileList) {//图片上传超过数量限制 this.$message.error('上传图片不能超过6张!'); console.log(file, fileList); }, imgUploadError(err, file, fileList){//图片上传失败调用 console.log(err) this.$message.error('上传图片失败!'); } } }
3.controller
@RequestMapping(value = "/imgUpload") public Wrapper imgUpload(HttpServletRequest req, MultipartHttpServletRequest multiReq) throws IOException { System.out.println("---" + fileUploadPath);//我这里用的springboot 在application.properties中配置,使用@Value 获取的文件上传目录 MultipartFile file = multiReq.getFile("file"); String originalFilename = file.getOriginalFilename(); String suffix = originalFilename.substring(originalFilename.indexOf(".")); String localFileName = MD5Util.md5(file.getInputStream()) + suffix; File localFile = new File(fileUploadPath + localFileName); if (!localFile.exists()) { localFile.createNewFile(); FileOutputStream fos = new FileOutputStream( localFile); FileInputStream fs = (FileInputStream) multiReq.getFile("img").getInputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = fs.read(buffer)) != -1) { fos.write(buffer, 0, len); } fos.close(); fs.close(); } else { log.info("文件已存在!!"); } return WrapMapper.wrap( Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE, "http://localhost:8080/img/" + localFileName);//这里是我执行封装的返回结果,也可以使用map, }
新闻热点
疑难解答
图片精选