uploading canvas context as image using ajax and php

前端 未结 1 1993
梦毁少年i
梦毁少年i 2020-12-18 07:42

I have a canvas and I want to upload the canvas context to the server using ajax and php. I want the final output to be an image stored on the server. I have done image uplo

相关标签:
1条回答
  • 2020-12-18 08:08

    This blog post aptly describes the method of saving canvases onto the server with AJAX queries, I guess this should be fitting for you.

    Basically, you will need a var canvasData = testCanvas.toDataURL("image/png"); to retrieve the canvas' contents in JavaScript. This will be a Base64 encoded string, something like this: data:image/png;base64,fooooooooooobaaaaaaaaaaar==.

    The following code will make sure the AJAX query sends the contents to the HTML:

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

    On the server, in the PHP script, you will have a key named HTTP_RAW_POST_DATA in the $GLOBALS array, this will contain the data we just fetched.

    // Remove the headers (data:,) part.
    $filteredData=substr($GLOBALS['HTTP_RAW_POST_DATA'], strpos($GLOBALS['HTTP_RAW_POST_DATA'], ",")+1);
    
    // Need to decode before saving since the data we received is already base64 encoded
    $decodedData=base64_decode($filteredData);
    
    $fp = fopen( 'test.png', 'wb' );
    fwrite( $fp, $decodedData);
    fclose( $fp );
    

    Of course, test.png is the filename you will save. The first line is required to remove the data:image/png;base64, part of the encoded image, so that it can later be decoded by base64_decode(). It's output ($decodedData) will be saved to the file.

    0 讨论(0)
提交回复
热议问题