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

充分了解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.jsp
        var curWwwPath = window.document.location.href;
        // uimcardprj/share/meun.jsp
        var pathName = window.document.location.pathname;
        var pos = curWwwPath.indexOf(pathName);
        // http://localhost:8083
        var localhostPaht = curWwwPath.substring(0, pos);
        // uimcardprj
        var projectName = pathName
            .substring(0, pathName.substr(1).indexOf('/') + 1);
        if (projectName == "/weixin" || projectName == "/admin"  || projectName == "/pc")
            projectName = "";
        return(localhostPaht + projectName);
    }

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

后端代码接收

public class UpLoadAction {
    @Autowired
    private PageService pageService;
    @Autowired
    private ImgService imgService;

    private String pageurl = System.getProperty("ROOT") + "/page"; // 上传页面的目录
    private String uploadPath = System.getProperty("ROOT") + "/img/lunbo"; // 上传图片的目录


    @RequestMapping("/uploadImage")
    @ResponseBody
    public 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里面的文件名对比,一致则取值.


今天你恰柠檬了咩