{{docContent.title}}

编辑框处理图片拖动和图片粘贴事件

关键代码如下

 /**
     * 显示html内容
     */
    public void showHtml() {
        WebEngine webEngine = htmlContent.getEngine();
        webEngine.loadContent("<h1>题目</h1><img style='width:100px;height:50px;' src='https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png' />");
    }

    /**
     * 编辑html文件
     */
    public void editHtml() {
        Stage stage = new Stage();
        final HTMLEditor htmlEditor = new HTMLEditor();
        stage.setScene(new Scene(htmlEditor));
        stage.setTitle("文档编辑器");
        stage.show();

        // 把编辑器加到主节点上
        Node node = htmlEditor.lookup(".top-toolbar");

        if (node instanceof ToolBar) {
            ToolBar bar = (ToolBar) node;
            Button btn = new Button("上传图片");
            btn.setPrefSize(100, 30);
            bar.getItems().add(btn);
            String img = "<img alt=\"Embedded Image\" src=\"http://doc.xiaoyou66.com/Public/Uploads/2020-07-05/5f0138fd785f2.png\" />";
            btn.setOnAction((ActionEvent event) -> {
                htmlEditor.setHtmlText(htmlEditor.getHtmlText() + img);
            });

            Button btn2 = new Button("获取内容");
            bar.getItems().add(btn2);
            btn2.setPrefSize(100, 30);
            btn2.setOnAction(event -> {
                System.out.println(htmlEditor.getHtmlText());
            });
        }

        // 设置html内容
        WebEngine webEngine = htmlContent.getEngine();
        htmlEditor.setHtmlText((String) webEngine.executeScript("document.documentElement.outerHTML"));

        // 处理拖动事件
        AtomicReference<String> content = new AtomicReference<>("");
        htmlEditor.setOnDragEntered(event -> {
            System.out.println("拖动事件,图片地址:"+ event.getDragboard().getFiles().get(0).getAbsolutePath());
            content.set(htmlEditor.getHtmlText());
        });
        htmlEditor.setOnDragExited(event -> {
            String url = event.getDragboard().getFiles().get(0).getAbsolutePath();
            htmlEditor.setHtmlText(content.get() + "<img src='file:///" + url + "'/>");
        });

        // 处理粘贴事件
        htmlEditor.addEventFilter(KeyEvent.KEY_PRESSED, e -> {
            if (e.isControlDown() && e.getCode() == KeyCode.V) {
                System.out.println("粘贴事件。。。。");
                htmlEditor.setHtmlText(htmlEditor.getHtmlText() + "<img src='data:image/jpeg;base64, " + modifyClipboard() + "'/>");

            }
        });


        // 关闭窗口的时候调用的事件
        stage.setOnCloseRequest(event -> {
            webEngine.loadContent(htmlEditor.getHtmlText());
        });

    }


    /**
     * 从剪贴板获取图片
     * @return 返回图片类型
     * @throws Exception 异常
     */
    public static Image getImageFromClipboard() throws Exception {
        java.awt.datatransfer.Clipboard sysc = Toolkit.getDefaultToolkit().getSystemClipboard();
        Transferable cc = sysc.getContents(null);
        if (cc == null) {
            return null;
        } else if (cc.isDataFlavorSupported(DataFlavor.imageFlavor)) {
            return (Image) cc.getTransferData(DataFlavor.imageFlavor);
        }
        return null;
    }

    /**
     * 剪贴板处理事件,这里我们可以获取很多内容
     * @return
     */
    private String modifyClipboard() {
        Clipboard clipboard = Clipboard.getSystemClipboard();
        System.out.println("从剪贴板获取文件路径:" + clipboard.getFiles());
        System.out.println("从剪贴板获取图片:" + clipboard.getImage());
        System.out.println("从剪贴板获取文字:" + clipboard.getString());
        System.out.println("从剪贴获取文件类型:" + clipboard.getContentTypes());
        if(clipboard.getImage()!=null){
            saveFile();
        }
        return "";
    }


    /**
     * 保存图片到本地
     */
    private void saveFile(){
        try {
            //获取粘贴板图片
            Image image = getImageFromClipboard();
            File file = new File("D:\\fileUpload\\1.png");
            //转成jpg
            //BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
            //转成png
            BufferedImage bufferedImage = new BufferedImage((int) image.getWidth(null), (int) image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
            Graphics2D g = bufferedImage.createGraphics();
            g.drawImage(image, null, null);
            //ImageIO.write((RenderedImage)bufferedImage, "jpg", file);
            ImageIO.write((RenderedImage) bufferedImage, "png", file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @FXML
    private void uploadTest(){
        System.out.println("上传图片测试");
        uploadImg("C:\\Users\\Administrator\\Pictures\\image.png");

    }



    /**
     * @description 模拟form表单,上传图片
     * @param fileName -- 图片路径
     * @return 接口返回的json数据
     * 原理:模拟form表单提交:把请求头部信息和和img 信息 写入到输出流中,
     * 通过流把img写入到服务器临时目录里,然后服务器再把img移到指定的位置
     * 最后通过写入流来获取post的响应信息。
     *
     */
    public void uploadImg(String fileName) {
        try {

            // 换行符
            final String newLine = "
";
            final String boundaryPrefix = "--";
            // 定义数据分隔线
            String BOUNDARY = "========7d4a6d158c9";
            // 服务器的域名
            URL url = new URL(API+"/upload");
            //"www.myhost.com",ECSheng=http://192.168.1.59/ecstore/index.php/openapi/syncnovo/image_upload ,即为form的action值
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置为POST情
            conn.setRequestMethod("POST");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求头参数
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Charsert", "UTF-8");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

            OutputStream out = new DataOutputStream(conn.getOutputStream());

            // 上传文件
            File file = new File(fileName);
            StringBuilder sb = new StringBuilder();
            sb.append(boundaryPrefix);
            sb.append(BOUNDARY);
            sb.append(newLine);
            // 文件参数,photo参数名可以随意修改
            sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + fileName
                    + "\"" + newLine);
            sb.append("Content-Type:image/jpeg");
            // 参数头设置完以后需要两个换行,然后才是参数内容
            sb.append(newLine);
            sb.append(newLine);

            // 将参数头的数据写入到输出流中
            out.write(sb.toString().getBytes());

            // 数据输入流,用于读取文件数据
            DataInputStream in = new DataInputStream(new FileInputStream(file));
            byte[] bufferOut = new byte[1024];
            int bytes = 0;
            // 每次读1KB数据,并且将文件数据写入到输出流中
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            // 最后添加换行
            out.write(newLine.getBytes());
            in.close();

            // 定义最后数据分隔线,即--加上BOUNDARY再加上--。
            byte[] end_data = (newLine + boundaryPrefix + BOUNDARY + boundaryPrefix + newLine)
                    .getBytes();
            // 写上结尾标识
            out.write(end_data);
            out.flush();
            out.close();


            // 定义BufferedReader输入流来读取URL的响应 ----读取返回的结果
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
                final String str ="\"data\":\"(.*?)\"";
                Pattern p= Pattern.compile(str);
                Matcher m=p.matcher(line);
                if(m.find()) {
                    String data = m.group();
                    System.out.println(API+data.substring(8,data.length()-1));
                }
            }

        } catch (Exception e) {
            System.out.println("发送POST请求出现异常!" + e);
            e.printStackTrace();
        }
    }