java springMVC+tinymce 实现ctrl+v 页面截图,上传图片功能

觉得上传图片太麻烦,就研究了下截屏复制上传,注意截图上传地址页面与保存不一样,是blob格式反扒的,所以要有个可以用来储存的隐藏地址。

截图上传效果图:

操作步骤:1.下载tinymce放到webapp下

2.引入包:    

   <script type="text/javascript" src="/js/zh_CN.js"></script>
    <script type="text/javascript" src="/jquery.form.js"></script>
    <script type="text/javascript" src="js/tinymce/jquery.tinymce.min.js"></script>
    <script type="text/javascript" src="tinymce/js/tinymce/tinymce.min.js"></script>
    <script type="text/javascript" src="tinymce/js/tinymce/langs/zh_CN.js"></script>
    <script type="text/javascript" src="tinymce/js/tinymce/plugins/uploadimage/plugin.min.js"></script>
    <script type="text/javascript" src="tinymce/js/tinymce/plugins/uploadimage/jquery.form.js"></script>
    <script type="text/javascript" src="/js/paste-upload-image.js"></script>

3.webapp/tinymce/js/tinymce/plugins 新建 uploadimage

并放入:jquery.form.js,plugin.min.js

plugin.min.js 文件内容:

tinymce.PluginManager.add('uploadimage', function (editor) {
    

    function selectLocalImages() {
        
        var dom = editor.dom;
        var input_f = $('<input type="file" name="file" accept="image/jpg,image/jpeg,image/png,image/gif" multiple="multiple">');
        input_f.on('change', function () {
            var form = $("<form/>",
                {
                    action: editor.settings.upload_image_url, //设置上传图片的路由,配置在初始化时
                    style: 'display:none',
                    method: 'post',
                    enctype: 'multipart/form-data'
                }
            );
            form.append(input_f);
            //ajax提交表单
            //alert(editor.settings.upload_image_url);
            form.ajaxSubmit({
                beforeSubmit: function () {
                    return true;
                },
                success: function (res) {
                    alert(res.data);
                    if (res.data!=null) {
                        editor.focus();
                        //tinyMCE 4.X版本的插入对象
                        tinyMCE.activeEditor.insertContent('<img name="xxx" src="'+res.data+'"></img>');
//                        editor.selection.setContent(dom.createHTML('img', {src: src}));
//                        data.file_path.forEach(function (src) {
//                            editor.selection.setContent(dom.createHTML('img', {src: src}));
//                        })
                    }
                    else
                        { alert('xxx');}
                }
            });
        });

        input_f.click();
    }
    editor.addCommand("mceUploadImageEditor", selectLocalImages);
    editor.addButton('uploadimage', {
        icon: 'image',
        tooltip: '上传图片',
        onclick: selectLocalImages
    });

    editor.addMenuItem('uploadimage', {
        icon: 'image',
        text: '上传图片',
        context: 'tools',
        onclick: selectLocalImages
    });
});

 

jsp 页面代码:

<div class="page-content">
                    <div class="row">
                        <div class="col-xs-12 col-sm-12">
                            <form class="form-horizontal" id="validation-form-contract">
                                <input type="hidden" name="pay_photo_id" id="pay_photo_id" value="${payment.id }" />
                                <div id="imgArea">
                                
                                </div>
                            </form>
                            <div class="row">
                                <form class="tinymce" style="text-align: center; min-height: 250px;"  enctype="multipart/form-data">
                                        <div class="col-xs-8" style="float: initial; margin: 0 auto;">
                                            <textarea name="mceContent" id="mceContent"></textarea>
                                        </div><!-- /.col -->
                                </form>
                            </div><!-- /.row -->
                        </div>
                    </div><!-- /.row -->
</div><!-- /.page-content -->    

 

js 

  <script type="text/javascript">
    globalcounter = 1;
    tinymce.init({
        selector: '#mceContent',
        width:600,
        height: 450,
        upload_image_url: 'xx/xx/xx', //配置的上传图片的地址
        plugins:  [  'image link code paste lists table',
                        'advlist autolink lists link  charmap print preview hr anchor pagebreak',
                          'searchreplace wordcount visualblocks visualchars code fullscreen',
                          'insertdatetime media nonbreaking save table contextmenu directionality',
                          'emoticons template paste textcolor colorpicker textpattern imagetools codesample toc help uploadimage',
                          'code paste'
                      ],
        templates: [
                      { title: 'Test template 1', content: 'Test 1' },
                      { title: 'Test template 2', content: 'Test 2' }
                    ],
                    content_css: [
                                  '//www.tinymce.com/css/codepen.min.css'
                                ], 
                   menubar: false,
                   
          toolbar1: 'undo redo | insert | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image',
        toolbar2: 'print preview media | forecolor backcolor emoticons | codesample help uploadimage',
        image_advtab: true,
        custom_undo_redo_levels: 10,
        paste_data_images: true,
        paste_preprocess: function(plugin, args) {
            args.content = args.content.replace("<img", "<img id=\"xxx_img_" + parseInt(globalcounter) + "\"");
            console.log(args.content);
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function(){
                if (this.readyState == 4 && this.status == 200){
                    upload(this.response);
                }
            };
            xhr.open('GET', args.content.split('"')[3]);
            xhr.responseType = 'blob';
            xhr.send();
            function upload(BlobFile){
                var x = new XMLHttpRequest();
                x.onreadystatechange = function(){
                    if( this.readyState == 4 && this.status == 200 ){
                        /* 返回的访问链接 */
                        data = this.responseText;
                        id = parseInt(globalcounter++);
                        console.log('response data: ' + data+'--id-'+id);
                        /* document.getElementById("pasted_image_" + id).src=data; */
                        /* 此处为获取ID为mce_1_ifr的iframe,再获取其下ID为xxx_img_x 的图片,然后更改图片的链接。不同版本下iframe的ID可能会不同,注意观察 */
                        //document.getElementById("mceContent_ifr").contentWindow.document.getElementById("xxx_img_" + id).setAttribute("src", "blob:http://127.0.0.1:8080/"+data.split(":")[3].split("\"")[1]);
                        var selem= document.getElementById('mceContent_ifr').contentWindow.document.getElementById("pasted_image_" + id).src;
                        $("#imgArea").append("<input type=\"hidden\" name=\"img_photo\" value=\""+selem+";"+data.split(":")[3].split("\"")[1]+"\">");
                        /*   $("#xxx_img_" + id).attr('alt',data); */
                    }
                };
                /* 使用post方法,上传的API为http://localhost:8080/uploadimg  */
                x.open('POST', 'xx/xx/xx2');//配置截图图片上传的地址
                x.send(BlobFile);
            }
        }
    });    
    </script>

 

后台代码:  

 @RequestMapping(value="/xx", method=RequestMethod.POST)
    public @ResponseBody ResponseResult  xx(@RequestParam("file") MultipartFile file, HttpServletRequest request){
        if (!file.isEmpty()) {
            String contextPath = request.getContextPath();
            String servletPath = request.getServletPath();
            String scheme = request.getScheme();
            
            String path = request.getSession().getServletContext().getRealPath("");// 项目路径
            path = path.substring(0,path.lastIndexOf(File.separator));// 项目上一级路径
            String url = File.separator + "upload" + File.separator + "payPhoto" + File.separator;            
            String storePath= path + url; 
            System.out.println("文件上传路径:"+storePath);
            String fileName = ToolsUtils.getUUID();
            if(file.getOriginalFilename().lastIndexOf(".") != -1) {
                fileName += file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."),file.getOriginalFilename().length());
            }
            File filepath = new File(storePath, fileName);
            if (!filepath.getParentFile().exists()) {
                filepath.getParentFile().mkdirs();//如果目录不存在,创建目录
            }
            try {
                file.transferTo(new File(storePath + fileName));//把文件写入目标文件地址
            } catch (Exception e) {
                e.printStackTrace();
                return new ResponseResult(false, "error", "");
            }
            return new ResponseResult(true, "ok", url + fileName);
        }else {
            return new ResponseResult(false, "error", "");
        }
    }
    
    @RequestMapping(value="/xx2", method=RequestMethod.POST)
    public @ResponseBody ResponseResult xx2(HttpServletRequest request){
        InputStream inputStream;
        try {
            inputStream = request.getInputStream();
            //获取请求头中Contect-Type的值
            // 图片后缀
            String imgSuffix = "png";
            Enumeration enumeration=request.getHeaderNames();
            while(enumeration.hasMoreElements()) {
                String name=(String)enumeration.nextElement();
                if(name.equals("content-type")){
                    String value=request.getHeader(name);
                    imgSuffix = value.split("/")[1];
                    logger.info("header中" + name + " " + value);
                    logger.info("文件后缀:" + xx);
                }
            }
            
            String contextPath = request.getContextPath();
            String servletPath = request.getServletPath();
            String scheme = request.getScheme();
            String path = request.getSession().getServletContext().getRealPath("");
             path = path.substring(0,path.lastIndexOf(File.separator));
            String url = File.separator + "upload" + File.separator + "payPhoto" + File.separator;   
            String storePath= path + url; 
            String fileName = ToolsUtils.getUUID()+"."+imgSuffix;
            
            File destFile = new File(storePath+fileName);
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            OutputStream outputStream = new FileOutputStream(destFile);
            // 缓冲区
            byte[] bs = new byte[1024];
            int len = -1;
            while ((len = inputStream.read(bs)) != -1) {
                outputStream.write(bs,0,len);
            }
            inputStream.close();
            outputStream.close();
            return new ResponseResult(true, "ok", url + fileName);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return new ResponseResult(false, "error", "");
        }
    }

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个使用SpringMVC和Vue.js实现图片的示例代码: 前端页面代码(使用Vue.js): ```html <template> <div> <input type="file" ref="fileInput" @change="handleFileUpload" multiple> <button @click="uploadFiles">上文件</button> </div> </template> <script> export default { data() { return { files: [] } }, methods: { handleFileUpload() { this.files = this.$refs.fileInput.files; }, uploadFiles() { let formData = new FormData(); for (let i = 0; i < this.files.length; i++) { formData.append("files", this.files[i]); } axios.post("/upload", formData, { headers: { "Content-Type": "multipart/form-data" } }).then(response => { console.log(response.data); }).catch(error => { console.log(error); }); } } } </script> ``` 后端代码(使用SpringMVC): ```java @PostMapping("/upload") @ResponseBody public List<String> upload(@RequestParam("files") MultipartFile[] files) throws IOException { List<String> fileNames = new ArrayList<>(); for (MultipartFile file : files) { if (!file.isEmpty()) { String fileName = file.getOriginalFilename(); String uuid = UUID.randomUUID().toString(); String saveFileName = uuid + "_" + fileName; file.transferTo(new File("/path/to/save/" + saveFileName)); fileNames.add(saveFileName); } } return fileNames; } ``` 这个示例代码使用了Vue.js来实现前端页面的交互,使用了axios库来发送文件上请求。后端使用了SpringMVC的MultipartFile来处理文件上请求。在处理每个文件时,可以根据需要对文件进行一些额外的处理,例如:获取文件大小、文件类型等。 希望这个示例代码可以帮助到您!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值