最近项目中遇到上传图片需携带跳转链接额外参数的问题困扰很久得到解决现记录如下

充分了解layui upload.js组件中的三个状态

choose,before,done

choose)表示文件选择后的回调,注意此时并没有加入上传队列;

before)表示文件上传前的回调,注意此时已经加入上传队列而且上传前before只会执行一次;

done)表示文件上传成功的回调,用来接收上传后返回的数据;

由于多文件上传我们的input是动态生成,before只运行一次,所以我们需要再before中拿取所有的值,并且拼接成JSON发送到后台,这样每次请求都会带上这个JSON,所以我们可以在后台判断对应的文件名是否相同,相同则取出里面的数据…

前台代码 使用each遍历数据

 var $,files;layui.use(['jquery','upload','carousel','layer'], function() {$ = layui.jquery,layer = layui.layer,upload = layui.upload;//图片预览var demoListView = $('#demoList'),uploadListIns = upload.render({elem: '#testList',url: getRootPath()+'/upload/uploadImage',multiple: true,auto: false,bindAction: '#testListAction',accept: 'images',data:{params:''},before: function(obj) {var map = [];layui.each($('input[name="img_href"]'), function (index, item) {map.push({"fileName":$(item).parents('td').prev().html(),"img_href":$(item).val()});});this.data.params = JSON.stringify(map)},choose: function(obj) {//files改为全局变量files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列//读取本地文件obj.preview(function(index, file, result) {$('#demo2').append('<img id="'+index+'" src="'+ result +'" alt="'+ file.name +'" style="height: 150px;" class="layui-upload-img">');var tr = $(['<tr id="upload-' + index + '">', '<td>'+file.name+'</td>','<td><input id="t-'+index+'" name="img_href" type="text" ></td>', '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>', '<td>等待上传</td>', '<td>','<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>', '</td>', '</tr>'].join(''));//删除tr.find('.demo-delete').on('click', function() {delete files[index]; //删除对应的文件$('#'+index).remove();tr.remove();uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值,以免删除后出现同名文件不可选});//单个重传tr.find('.demo-reload').on('click', function(){obj.upload(index, file);});demoListView.append(tr);});},done: function(res, index, upload) {if (res.code == "0") { //上传成功var tds =  $('#upload-' + index).children();tds.eq(3).html('<span style="color: #5FB878;">上传成功</span>');tds.eq(4).html(''); //清空操作return delete this.files[index]; //删除文件队列已经上传成功的文件}this.error(index, upload);},error: function(index, upload) {//上传出错var tr = demoListView.find('tr#upload-' + index),tds = tr.children();tds.eq(3).html('<span style="color: #FF5722;">上传失败</span>');tds.eq(4).find('.demo-reload').removeClass('layui-hide'); //显示重传}});});var getRootPath = function() {// http://localhost:8083/uimcardprj/share/meun.jspvar curWwwPath = window.document.location.href;// uimcardprj/share/meun.jspvar pathName = window.document.location.pathname;var pos = curWwwPath.indexOf(pathName);// http://localhost:8083var localhostPaht = curWwwPath.substring(0, pos);// uimcardprjvar projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);if (projectName == "/weixin" || projectName == "/admin"  || projectName == "/pc")projectName = "";return(localhostPaht + projectName);}

其中getRootPath是获取工程路径的方法

后端代码接收

public class UpLoadAction {@Autowiredprivate PageService pageService;@Autowiredprivate ImgService imgService;private String pageurl = System.getProperty("ROOT") + "/page"; // 上传页面的目录private String uploadPath = System.getProperty("ROOT") + "/img/lunbo"; // 上传图片的目录@RequestMapping("/uploadImage")@ResponseBodypublic JSONObject uploadImage(@RequestParam("file") MultipartFile file, String params) {String href = null;List<ImgHrefVo> testDemos = JSON.parseArray(params, ImgHrefVo.class);
//通过遍历获取当前图片对应的超链接即文本框中输入的内容for (int i = 0; i < testDemos.size(); i++) {if(testDemos.get(i).getFilename().equals(file.getOriginalFilename())){href = testDemos.get(i).getImg_href();break;}}JSONObject res = new JSONObject();JSONObject resUrl = new JSONObject();if (!file.isEmpty()) {Map<String, String> resObj = new HashMap<>(CharsetMapping.MAP_SIZE);try {//得到旧文件名String oldFileName =file.getOriginalFilename();//得到后缀名int index =oldFileName.lastIndexOf(".");String extName =oldFileName.substring(index);//新文件名String newFileName=System.nanoTime()+extName;File savePathFile =new File(uploadPath);if (savePathFile.exists()==false){savePathFile.mkdirs();}BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(uploadPath, newFileName)));out.write(file.getBytes());int n = imgService.addImage(newFileName,"img/lunbo"+newFileName,1,href);System.out.println(n);out.flush();out.close();} catch (IOException e) {res.put("code", 1);res.put("msg", "上传出错");res.put("data", resUrl);return res;}res.put("code", 0);res.put("msg", "上传成功");res.put("data", resUrl);return res;} else {res.put("code", 0);res.put("msg", "上传为空");res.put("data", resUrl);return res;}}
}

这边请大家自行调整,json里面我们可以存两个.一个是参数,一个是文件名,这样到后台我们可以拿取文件名和json里面的文件名对比,一致则取值.

layui上传图片需携带额外参数相关推荐

  1. el-upload上传文件携带额外参数

    在进行文件上传时,需要传递其他参数,比如下图中需要实现携带下拉框的参数 前端实现:将下拉框中的参数 传递到:data中 :data="{'script_model':script_model ...

  2. layui upload上传携带额外参数

    data 可以在 bofore 中追加 ,before: function(obj) { this.data = {"key1": "value"," ...

  3. iview upload 上传时携带额外参数

    可以直接放到组件里用, "action"改为自己的接口路径: 效果:点击看效果图 <template><Form :model="formItem&qu ...

  4. VUE 子组件向父组件传值(含传多值以及添加额外参数场景)

    一.子组件向父组件传递一个值 子组件: this.$emit('change', this.value); 父组件: <!-- 在父组件中使用子组件 --> <editable-ce ...

  5. layui跳转html如何带参数,Layui跳转页面代码(可携带复杂参数)

    今天用了Layui的"数据表格 - 数据操作"示例代码,结果发现点击"编辑"按钮出出来一个弹出消息框,效果如下: 虽然说也可以用"弹出层"做 ...

  6. layui upload 额外参数上传

    layui 2.0.x upload 额外参数上传 <div class="layui-inline" style="margin-top: 5px;"& ...

  7. Layui数据表格请求添加参数

    Layui数据表格基本形态,官网链接地址 <!DOCTYPE html> <html><head><meta charset="utf-8" ...

  8. data参数 layui_layui upload 额外参数上传

    layui 2.0.x upload 额外参数上传 机型 版本描述 选择文件 开始上传 layui.use(['upload','element','form'], function () { var ...

  9. vue 自定义事件 传入额外参数

    <div @click="myClick">我是子组件内容<div>//子组件自定义事件 myClick(){this.emit("childCl ...

最新文章

  1. C++ 统计字符串中某字符出现的次数
  2. android service中显示一个dialog
  3. 新鲜高频笔面试题分享,Redis、MongoDB、ElasticSearch...
  4. linux驱动编写(看门狗)
  5. JSP之【include】指令
  6. maccms代码审计——前台sql注入漏洞
  7. 7-12 求和:m+mm+mmm+mmmm+ ... +mmm……mmm(n个m)
  8. 小程序云开发(四):云数据库的文件操作之上传头像图片,获取云图片
  9. 自主招生计算机网测考什么,自主招生是什么意思 2019自主招生考试考什么
  10. nginx基础:nginx访问限制
  11. [1191]电脑耳机孔插上耳机没反应
  12. 移动端网页签名,附上DOM,效果图
  13. 搭建一个用于工作和学习的Linux桌面环境的尝试
  14. 关于单页应用(SPA)的经验之谈
  15. wav avi计算机存储音频,把AVI和WAV文件合二为一
  16. 【bzoj2259】[Oibh]新型计算机 堆优化Dijkstra
  17. Wireshark各版本下载地址
  18. 电气工程及其自动化专业英语复习
  19. springboot环境配置,yml格式,不同环境切换
  20. 【C4D基础】导入图片、选择工具、线性切割、显示与渲染、旋转

热门文章

  1. windows下qt程序报错“the inferior stopped because it triggered an exception”
  2. 超快!三分钟学会用3DsMax制作波浪效果!大忙人的你也可以忙里偷闲学技术
  3. Github标星25K+超火的Android实战项目,2022BTAJ面试真题详解
  4. LabVIEW使用VI Server的时候出现1003错误
  5. Oracle关于分组小计再合计
  6. 数据资产盘点实践:智能对标
  7. 【Windows】虚拟机配置及Win7电脑搭建服务器
  8. GridView合并单元格求和方法
  9. 店铺如何提升流量,抢占先机
  10. 北京内推 | 微软研究院科学智能中心招聘多模态学习方向研究实习生