上传组件重写,添加了预览,在使用多个的上传组件时预览有问题,但是不影响正常预览

<template><div class="weui-cell"><div class="weui-cell__bd"><div class="weui-uploader"><div v-show="showHeader" class="weui-uploader__hd"><p class="weui-uploader__title"> {{ title }} </p><div v-show="showHeader && showTip" class="weui-uploader__info">{{ list.length }} / {{ max }}</div></div><div class="weui-uploader__bd" :class="{small: size === 'small'}"><ul class="weui-uploader__files"><div><div v-for="(item, index) in list" class="weui-uploader__file" style="position:relative;"><uploader-item class="previewer-demo-img" :background-image="item.src" :key="item.src" @click.native="preview(item, index)" style="float: right;"></uploader-item><!--<img class="previewer-demo-img" width="65px" height="65px" :src="item.src" @click ="preview(item, index)" style="float: right;">--><div v-if="!handleClick"><x-icon type="ios-close" size="20" style="position:absolute;margin-left: 40px" @click.native="remove(item, index)"></x-icon></div></div><div v-transfer-dom><previewer :list="HDImg" ref="previewer" :options="options"></previewer></div></div></ul><div v-show="!readonly && list.length < max" class="weui-uploader__input-box" @click="add"><input v-if="!handleClick" ref="input" class="weui-uploader__input" type="file" accept="image/jpg,image/jpeg,image/png,image/gif" :capture="showCapture" @change="change"></div></div></div></div><toast v-model="showPositionValue" type="warn"  :time="1500" is-show-mask  >网络异常,请检查网络</toast><toast v-model="uploadFailure" type="warn"  :time="1500" is-show-mask  >上传失败</toast></div>
</template><script>
import UploaderItem from './uploader-item.vue'
import {Previewer, TransferDom, Toast} from 'vux'
import axios from 'axios'
export default {name: 'upload',props: {list: {type: Array,default: () => []},HDImg: {type: Array,default: () => []},max: {type: Number,default: 1},val: { // 传递为上传图片的种类type: String,default: ''},showHeader: {type: Boolean,default: true},showTip: {type: Boolean,default: true},readonly: {type: Boolean,default: false},title: {type: String,default: '图片上传'},attachIds: { // 回调主键集合type: Array,default: () => []},// 是否接管+号的click事件,如果是,点击不弹出选择文件的框handleClick: {type: Boolean,default: false},// 选择文件后是否自动上传,如果不是,则emit change事件autoUpload: {type: Boolean,default: true},uploadUrl: {type: String,default: ''},size: {type: String,default: 'normal'},capture: {type: String,default: ''},params: {type: Object,default: null}},components: {UploaderItem,Previewer,Toast},directives: {TransferDom},data () {return {options: {getThumbBoundsFn (index) {// find thumbnail elementlet thumbnail = document.querySelectorAll('.previewer-demo-img')[index]// get window scroll Ylet pageYScroll = window.pageYOffset || document.documentElement.scrollTop// optionally get horizontal scroll// get position of element relative to viewportlet rect = thumbnail.getBoundingClientRect()// w = widthreturn {x: rect.left, y: rect.top + pageYScroll, w: rect.width}// Good guide on how to get element coordinates:// http://javascript.info/tutorial/coordinates},isClickableElement: function (el) {return /previewer-delete-icon/.test(el.className)}},showPositionValue: false,rmObj: {},uploadFailure: false}},methods: {add () {if (this.handleClick) {this.$emit('add-image')}this.$emit('add-image', this.val)},// 移除第一张图 本身只移除页面数组值 调用组件可自行在外实现后台操作remove (obj, index) {if (this.handleClick) {// 可屏蔽this.$emit('remove-image', this.rmObj, index)} else {// 删除当前张this.rmObj = this.list.splice(index, 1)this.HDImg.splice(index, 1)this.$emit('remove-image', this.rmObj, index)}},preview (item, index) {// 暂未实现,可以捕捉preview事件自己实现this.$refs.previewer.show(index)this.$emit('preview', item, index)// this.$emit('preview', image)},// 适用于action的情况change () {if (this.handleClick) {return}let formData = new window.FormData()formData.append('file', this.$refs.input.files[0])formData.append('type', this.val)if (this.params) {for (let key in this.params) {formData.append(key, this.params[key])}}if (this.autoUpload) {if (!this.uploadUrl) {console.error('uploadUrl不应为空')}if (this.$vux && this.$vux.loading) {this.$vux.loading.show('正在上传')}let _this = thisaxios.post(this.uploadUrl, formData).then((response) => {if (this.$vux && this.$vux.loading) {this.$vux.loading.hide()}if (response.data.result === '0') {this.$refs.input.value = ''console.info(response.data)if (!this.CommonUtils.isNotExists(response.data.attachId)) {console.info('response.data.attachId:' + response.data.attachId)this.attachIds.push(response.data.attachId)console.info(this.attachIds)}// this.images.push(response.data.data)// 缩略图  http://192.168.**.**:1111/oms/static/attachment/20180619/1806191459180001_1.jpgthis.list.push({src: `${response.data.data.url}`})// 高清图  http://192.168.**.**:1111/oms/static/attachment/20180619/1806191459180001_2.jpglet _src = response.data.data.urllet i = _src.lastIndexOf('.') - 1let last = _src.substr(0, i) // 前半部分let end = _src.substr((i + 1), _src.length) // 后半部分_src = last + '2' + end// console.info('_src:')// console.info(_src)this.HDImg.push({src: `${_src}`})} else {_this.uploadFailure = true}}).catch(function () {_this.$vux.loading.hide()_this.showPositionValue = true})} else {this.$emit('upload-image', formData)}}},computed: {showCapture () {return this.capture || undefined}}
}
</script>
<style scoped lang="less">
@import '~vux/src/styles/weui/widget/weui-uploader/index.less';
.remove:before {width: 0;height: 0;
}
.weui-uploader__bd.small {.weui-uploader__input-box {margin-right: 5px;margin-bottom: 5px;width: 63px;height: 63px;}.weui-uploader__file {width: 65px;height: 65px;margin-right: 5px;margin-bottom: 5px;}
}
.vux-x-icon {/*fill: #F70968;*//*fill: rgba(212,212,212,1);*/fill: rgba(248,93,55,0.8);
}
.cell-x-icon {display: block;fill: green;
}
</style>
/**
 * 上传附件
 *
 * @param file 原图片
 *
 */
@RequestMapping("/uploadAttachment")
public R uploadAttachment(@RequestBody MultipartFile file, HttpServletRequest request,@RequestParam(name = "type", required = false) String type) {// 返回参数
   Map<String, Object> map = new HashMap<String, Object>();Map<String, Object> mapData = new HashMap<String, Object>();String attachmentPath = C.PhotoPath.ATTACHMENT + DateKit.getCurrentDate(new Date(), "yyyyMMdd") + "/";// 图片显示路径(存数据库)==>路径+当前年月日
   String httpPath = globalPropsConfig.getHttpPath() + attachmentPath;// 图片存放路径 ==>路径+当前年月日
   String path = globalPropsConfig.getImgPath() + attachmentPath;// 1、处理原图,上传原图到服务器
   // 图片保存的路径,不含最下层文件夹
   LOGGER.info("path:" + path);// 获取原图文件名
   String name = file.getOriginalFilename();// 判断文件的MIMEtype
   String imgType = file.getContentType();if (imgType == null || !imgType.toLowerCase().startsWith("image/")) {return R.error("不支持的文件类型,仅支持图片!");}if (!imgType.toLowerCase().endsWith(".jpg") || !imgType.toLowerCase().endsWith(".jpge")|| !imgType.toLowerCase().endsWith(".png")|| !imgType.toLowerCase().endsWith(".bmp")) {return R.error("不支持的文件类型,仅支持图片!");}// LOGGER.info("file ImgType:" + imgType);
   // 更改文件名
   String id = UuidKit.getSmallUNID();String originalImgName = id + "_1" + name.substring(name.lastIndexOf('.'));// String originalImgName = new Date().getTime() + "" + new Random().nextInt(10000) + "_1"
   // + name.substring(name.lastIndexOf('.'));
   String originalImgPath = path + originalImgName;LOGGER.info("文件路径:" + path + ":" + originalImgName);// 准备上传
   File targetFiles = new File(path);File targetFile = new File(path, originalImgName);// 上传
   try {// 判断目标文件夹是否存在,不存在,则创建
      if (!targetFiles.exists()) {targetFiles.mkdirs();}// 将原图上传到服务器
      targetFile.createNewFile();file.transferTo(targetFile);// 2、根据原图文件产生高清图文件并上传至服务器,高清图压缩为800K
      String detailImgName = id + "_2" + name.substring(name.lastIndexOf('.'));// 高清图存放路径
      String detailImgPath = path + detailImgName;PicKit.commpressPicForScale(originalImgPath, detailImgPath, 800, 0.9);LOGGER.info("高清图上传完成!路径为:" + detailImgPath);// 3、根据原图文件产生缩略图文件,缩略图大小比例16x16寸
      String thumbnailName = id + "_3" + name.substring(name.lastIndexOf('.'));// 缩略图存放路径
      String thumbnailPath = path + thumbnailName;PicKit.reduceImg(originalImgPath, thumbnailPath, 60, 60, null);LOGGER.info("缩略图上传完成!路径为:" + thumbnailPath);// 4、上传文件新增入库
      Attachment attachment = new Attachment();attachment.setPkid(id);attachment.setThumbnail(httpPath + thumbnailName);attachment.setDetailImg(httpPath + detailImgName);attachment.setOriginalImg(httpPath + originalImgName);attachment.setType(type);attachment.setStatus(C.Status.NOMAL);attachment.setCreateTime(new Date());attachmentService.save(attachment);// 5、回传参数
      mapData.put("url", httpPath + thumbnailName);map.put("result", "0");map.put("message", "附件上传成功");map.put("attachId", id);map.put("data", mapData);} catch (Exception e) {LOGGER.info("附件上传失败:" + e);e.printStackTrace();mapData.put("url", "");map.put("result", "-1");map.put("message", "附件上传失败,请重新上传!");map.put("attachId", "");map.put("data", mapData);}return R.ok(map);
}

vux-upload组件相关推荐

  1. vue实战(1)——解决element-ui中upload组件使用多个时无法绑定对应的元素

    解决element-ui中upload组件使用多个时无法绑定对应的元素 以前写的项目关于图片上传的都是单张或几张图片上传(主要是基于vue的element),图片路径都是固定写的,所以遇见过列表中多个 ...

  2. element-ui upload组件上传图片时限制图片宽高

    template部分代码,引入upload组件,这里采用自动上传文件 <div class="filesC"> <el-upload ref="file ...

  3. vue中使用elmentUI的Upload组件提交文件和后台接收

    1.参考此博客,希望有以下知识储备 vue的路由,跨域请求,springboot2.X,html,已经阅读elementUI官网中关于upload组件的详细介绍. 2.废话不多说,直接讲解细节. 前台 ...

  4. antd 上传进度_antd vue upload组件使用customRequest上传文件显示文件上传进度

    antd-vue上传文件upload组件使用自定义上传方法customRequest无法显示文件上传进度条,如下图红框内的进度条无法显示当前文件上传进度 于是,在网上搜索解决方案: 第一种解决方案是自 ...

  5. layui如何集成文件服务器,layui使用upload组件实现文件上传功能

    layui使用upload组件实现文件上传功能 发布时间:2020-05-22 17:25:25 来源:亿速云 阅读:309 作者:鸽子 背景:页面上一个按钮,点击弹出上传框,从按钮的方法代码开始写: ...

  6. 阿里云OSS 服务端签名后直传之分片上传(结合element-ui的upload组件)

    分片上传(结合element-ui的upload组件实现自定义上传) async uploadFree(content){let data = await this.getOssToken(); // ...

  7. ant design 预览图片_AntD框架的upload组件上传图片时遇到的一些坑

    前言 本次做后台管理系统,采用的是 AntD 框架.涉及到图片的上传,用的是AntD的 upload 组件. 前端做文件上传这个功能,是很有技术难度的.既然框架给我们提供好了,那就直接用呗.结果用的时 ...

  8. Fusion Upload组件 对接 阿里云OSS/七牛/又拍

    BeforeUpload 方法 Upload组件的BeforeUpload方法,是一个十分强大的方法,可以在上传请求发起之前做一系列的操作行为.从而达到改变请求参数的目的. beforeUpload ...

  9. element upload预览_vue2.0 使用element-ui里的upload组件实现图片预览效果方法

    1.首先我们在cli中引入element-ui 2.然后在具体的代码中放入uoload组件 点击上传 只能上传jpg/png文件,且不超过500kb 3.使用element-ui的upload组件中提 ...

  10. element-ui upload组件 上传文件类型限制

    element-ui upload组件 上传文件类型限制 <el-uploadclass="c-upload"ref="upload":action=&q ...

最新文章

  1. pymysql模块操作数据库及连接报错解决方法
  2. STM32 基础系列教程 28 - USB_DFU
  3. 推荐一款好用的redis客户端工具
  4. PyQt4 开发入门
  5. HDU 2588 GCD(欧拉函数)
  6. Apache JMeter 压试 HTTP接口
  7. 传统手工特征深度特征【转载】
  8. Spring Cloud Config 规范 1
  9. 查看python安装路径以及pip安装的包列表及路径
  10. 华为在鸿蒙的另一张王牌,华为的这两张王牌,将助力Mate40系列角逐安卓机皇的位置...
  11. 微信全球MBA创新大赛Roadshow最终站火爆中欧
  12. vue - 禁止input[number]输入 +、-、e 符号,并且只能输入两位小数
  13. medusa安装和简单使用
  14. Python学习教程-1_Introductions
  15. 【NOIP2015】洛谷2668 斗地主
  16. 4月21日V反再次来临?
  17. ASEMI线性稳压电源芯片AMS1117-3.3参数及接线电路图
  18. 缠论是一种交易方法炒股是不是一定要学习缠论(利用缠论如何选股)
  19. 数字点播院线三级设备开发总结
  20. Python爬虫系列之MeiTuan优选商家端商品自动化管理(商品发布、商品排期、订单采集)

热门文章

  1. 一文读懂GoogLeNet神经网络
  2. 反汇编引擎实现——流程分析
  3. java 微博sdk_Java新浪微博客户端开发第一步
  4. Aleph1堆栈溢出例子调试过程
  5. class jqprint 失效_响应式状态时的jqprint打印
  6. 重新安装ROG Armoury Crate
  7. 简约而不简单epoll之EPOLLRDHUP
  8. Mysql的锁(自用笔记)
  9. 社区观点 | 关于比原链MOV巡查官制度的几点思考
  10. matlab:查看使用内存空间情况