无法上载canvas.toDataURL映像:不赞成在主线程上使用同步XMLHttpRequest


cannot upload a canvas.toDataURL image: Synchronous XMLHttpRequest on the main thread is deprecated

我无法上传canvas.toDataURL图像:我收到警告:

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help http://xhr.spec.whatwg.org/

然后错误:

no element found testSave.php:23:1

在本教程中,我的JavaScript是:

var canvasData = testCanvas.toDataURL("image/png");
var ajax = new XMLHttpRequest();
ajax.open("POST",'testSave.php',false);
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(canvasData );

和testSave.php:

<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
  // Get the data
  $imageData=$GLOBALS['HTTP_RAW_POST_DATA'];
  // Remove the headers (data:,) part.
  // A real application should use them according to needs such as to     check image type
  $filteredData=substr($imageData, strpos($imageData, ",")+1);
  // Need to decode before saving since the data we received is already base64 encoded
  $unencodedData=base64_decode($filteredData);
//echo "unencodedData".$unencodedData;
// Save file. This example uses a hard coded filename for testing,
// but a real application can specify filename in POST variable
$fp = fopen( 'test.png', 'wb' );
fwrite( $fp, $unencodedData);
fclose( $fp );
}
?>

我发现了一个丑陋的问题解决方案:

  1. 在HTML <head>中,添加:

<script src="../static/js/jquery-1.11.2.js"></script>

  1. 将问题的JavaScript部分替换为:

    var dataURL = canvas.toDataURL('image/png');
    $.ajax({
    type: "POST",
    url: "upload_ajax",
    data: { 
       imgBase64: dataURL
      }
    }).done(function(o) {
    console.log('saved'); 
    // If you want the file to be visible in the browser 
    // - please modify the callback in javascript. All you
    // need is to return the url to the file, you just saved 
    // and than put the image in your browser.
    });
    
  2. 使用Flask而不是PHP,代码的相关部分是:

from flask import json as jsonflask import cv2 import uuid import os import base64 import numpy as np import StringIO import urllib from PIL import Image

def request_to_nparray(request): output=request.form['imgBase64'] head = "data:image/png;base64," assert(output.startswith(head)) imgdata = base64.b64decode(output[len(head):]) imgF = StringIO.StringIO() imgF.write(imgdata) imgF.seek(0) img = Image.open(imgF) buf = np.fliplr(np.asarray(img)) buf = np.asarray(img) bufshape=buf.shape rgbFrame = np.zeros(bufshape, dtype=np.uint8) rgbFrame[:, :, 0] = buf[:, :, 2] rgbFrame[:, :, 1] = buf[:, :, 1] rgbFrame[:, :, 2] = buf[:, :, 0] ourframe = np.copy(rgbFrame) return ourframe

`@app.route('/upload_ajax', methods = ['POST'])
def ajax_request():
    photo_array= request_to_nparray(request)
    f_name = str(uuid.uuid4()) + '.jpg'
    _photo_path= os.path.join(app.config['UPLOAD_FOLDER'], f_name)
    cv2.imwrite(_photo_path, photo_array)
    return jsonflask.dumps({'filename':f_name})`