wangEditor图片批量上传

 

执行效果如下图所示

 

js代码

    //4.初始化编辑器
    var E = window.wangEditor;
    var editor = new E('#bizImg');
    editor.customConfig.uploadFileName = 'files'; //设置文件上传的参数名称
    editor.customConfig.uploadImgServer = '/serviceMerchantBiz/upload';// 上传图片到服务器
    editor.customConfig.uploadImgMaxSize = 3 * 1024 * 1024; // 将图片大小限制为 3M
    //自定义上传图片事件
    editor.customConfig.uploadImgHooks = {
        before : function(xhr, editor, files) {},
        success : function(xhr, editor, result) { console.log("上传成功"); },
        fail : function(xhr, editor, result) { console.log("上传失败,原因是"+result);},
        error : function(xhr, editor) { console.log("上传出错");},
        timeout : function(xhr, editor) { console.log("上传超时");},
        customInsert: function (insertImg, result, editor) {
            // insertImg 是插入图片的函数,editor 是编辑器对象,
            // result 是服务器端返回的结果必须是一个JSON格式字符串,多个图片地址组成的数组
            for(var j=0;j<result.data.length;j++){
                insertImg(result.data[j]);
            }
        }
    };
    editor.create();
 /**
     * 上传图片
     */
    @RequestMapping(value = "/upload", produces = {"text/html;charset=UTF-8"},method=RequestMethod.POST)
    @ResponseBody
    public String upload(@RequestPart("files") List<MultipartFile> files, HttpServletRequest request) {
        //获取文件上传目录
        String path= getClass().getResource("/").getPath();
        path= path+"static"+File.separator+"uploadfiles";
        if(files != null && files.size() > 0){
            //封装返回数据
            Map<String, Object> map = new HashMap<>();
            String imgUrls[] = new String[files.size()];
            for (int i=0; i<files.size(); i++) {
                //获取文件扩展名
                String extName = FilenameUtils.getExtension(files.get(i).getOriginalFilename());
                //生成新的文件名
                String fileName = UUID.randomUUID().toString() + FilenameUtils.EXTENSION_SEPARATOR + extName;
                //创建空文件对象
                File targetFile = new File(path, fileName);
                // 检测是否存在目录
                if (!targetFile.getParentFile().exists()) {
                    targetFile.getParentFile().mkdirs();
                }
                //上传图片
                try {
                    files.get(i).transferTo(targetFile);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //拼装上传后的图片地址
                String url = request.getContextPath() + "/static/uploadfiles/" + fileName;
                //存储到字符串数组
                imgUrls[i] = url;
            }
            map.put("error",0);
            map.put("data", imgUrls);
            return JSONArray.toJSONString(map);
        }
        return null;
    }

有问题留言。

 

 

 

 

 

 

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值