• 用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>
  • 相关阅读:
    布局及视图(三)
    笔试中的编程题2
    布局及视图(四)
    SoftReference,WeakReference&WeakHashMap
    Android自用 监测网络是否可用
    Android自用 加载png图片时出错!
    Android访问权限大全
    笔试中的编程题3
    如何全面的把握一个系统的异常处理
    从程序的控制逻辑看线程的三种应用模式
  • 原文地址:https://www.cnblogs.com/liulinjie/p/5852210.html
Copyright © 2020-2023  润新知