• 用HTML5 File API 实现截图粘贴上传、拖拽上传


    <!DOCTYPE html>
    <html>
    <head>
    <title>test chrome paste image</title>
    <style>
    DIV#editable {
    400px;
    height: 300px;
    border: 1px dashed blue;
    }
    </style>
    <script type="text/javascript">
    window.onload = function () {
    function paste_img(e) {
    if (e.clipboardData.items) {
    ele = e.clipboardData.items
    for (var i = 0; i < ele.length; ++i) {
    if (ele[i].kind == 'file' && ele[i].type.indexOf('image/') !== -1) {
    var blob = ele[i].getAsFile();
    window.URL = window.URL || window.webkitURL;
    var blobUrl = window.URL.createObjectURL(blob);
    console.log(blobUrl);
    var new_img = document.createElement('img');
    new_img.setAttribute('src', blobUrl);

    document.getElementById('editable').appendChild(new_img);
    convertImgToBase64(blobUrl, function (base64Img) {
    // console.log(base64Img);
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/ajax', true);
    xhr.setRequestHeader('Content-Type', 'application/json')
    xhr.onreadystatechange = function () {
    if (xhr.readyState == xhr.DONE && /^2d{2}$/.test(xhr.status)) {
    }
    }
    xhr.send(base64Img);//把body字符串作为请求体发送到服务器端
    });
    }

    }
    } else {
    alert('non-chrome');
    }
    }
    document.getElementById('editable').onpaste = function () {
    paste_img(event);
    return false;
    };
    }

    function convertImgToBase64(url, callback, outputFormat) {
    var canvas = document.createElement('CANVAS'),
    ctx = canvas.getContext('2d'),
    img = new Image;
    img.crossOrigin = 'Anonymous';
    img.onload = function () {
    canvas.height = img.height;
    canvas.width = img.width;
    ctx.drawImage(img, 0, 0);
    var dataURL = canvas.toDataURL(outputFormat || 'image/png');
    callback.call(this, dataURL);
    canvas = null;
    };
    img.src = url;
    }
    </script>
    </head>
    <body>
    <div id="non-editable">
    <!--<img src="./1.jpg"/>-->
    </div>
    <div id="editable" contenteditable="true">
    </div>
    </body>
    </html>
  • 相关阅读:
    Premiere&After Effects的实时预览插件开发
    Mac OS平台下应用程序安装包制作工具Packages的使用介绍(补充)
    kattle 发送post请求
    mybatis 动态sql表达式相关应用
    Echarts 之三 —— 地市联动数据统计二
    Echarts 之二——地市联动数据统计
    java 版本EChart使用
    dragsort html拖拽排序
    html iframe 元素之间的调用
    ORACLE lag()与lead() 函数
  • 原文地址:https://www.cnblogs.com/liulinjie/p/5852210.html
Copyright © 2020-2023  润新知