使用php在文件夹中上传图像创建文件路径

时间:2017-07-19 09:39:47

标签: php mysqli webcam webcam-capture webcam.js

使用Photo Booth by vamapaull  我正在尝试捕获文件夹中的图像。我的sql工作正常,但将其更改为mysqli无法上传.webcam捕捉但不存储图像文件夹。(在wamp上)。在存储的图像输出中查看幻灯片放映ID明智。

 Table name  uploadimages ::   ID   Name    image   user_id 
    veiw.php
============================
<script type="text/javascript">
    hs.graphicsDir = 'graphics/';
    hs.align = 'center';
    hs.transitions = ['expand', 'crossfade'];
    hs.wrapperClassName = 'dark borderless floating-caption';
    hs.fadeInOut = true;
    hs.dimmingOpacity = .75;

    // Add the controlbar
    if (hs.addSlideshow) hs.addSlideshow({
        //slideshowGroup: 'group1',
        interval: 5000,
        repeat: false,
        useControls: true,
        fixedControls: 'fit',
        overlayOptions: {
            opacity: .6,
            position: 'bottom center',
            hideOnMouseOut: true
        }
    });
</script>
<script src="swfobject.js" language="javascript"></script>
        <script type="text/javascript">
            var flashvars = {};

            var parameters = {};
            parameters.scale = "noscale";
            parameters.wmode = "window";
            parameters.allowFullScreen = "true";
            parameters.allowScriptAccess = "always";

            var attributes = {};

            swfobject.embedSWF("take_picture.swf", "main", "700", "400", "9", 
                    "expressInstall.swf", flashvars, parameters, attributes);
        </script>

        <script type="text/javascript">
            var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
            document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
        </script>

        <script type="text/javascript">
            var pageTracker = _gat._getTracker("UA-3097820-1");
            pageTracker._trackPageview();
        </script>
        <script type="text/javascript">
    var mainswf = new SWFObject("take_picture.swf", "main", "600", "400", "9", "#ffffff");
    mainswf.addParam("scale", "noscale");
    mainswf.addParam("wmode", "window");
    mainswf.addParam("allowFullScreen", "true");
    //mainswf.addVariable("requireLogin", "false");
    mainswf.write("flashArea");

 </script>

php code

<?php
    session_start();
    //This project is done by vamapaull: http://blog.vamapaull.com/
    include_once('db.php');
    if(isset($GLOBALS["HTTP_RAW_POST_DATA"])){
        $jpg = addslashes($GLOBALS["HTTP_RAW_POST_DATA"]);
        $img = addslashes($_GET["img"]);
        //$id= $_GET["id"];
        $vid=$_SESSION['vid'];
        //$image =addslashes(file_get_contents($_FILES["img"]["tmp_name"]));
        //$image_name = addslashes($_FILES["image"]["name"]);
        $filename = "images/poza_". mktime(). ".jpg";
        file_put_contents($filename, $jpg);
        mysqli_query($db  ,"INSERT INTO uploadimages (Name,image,user_id) VALUES ('$filename','$jpg','$vid')")or die(mysqli_error($db));
        } else{
        echo "Encoded JPEG information not received.";
    }
    ?>

 -------------------------
 Other files can be seen at link given 
http://vamapaull.com/photo-booth-flash-webcam-image-capture/  This how directory looks like.image attached.

Directory looks like this

1 个答案:

答案 0 :(得分:0)

您可能会考虑使用一些新的(?)HTML5方法,而不是依赖于过时且很快被遗忘的技术(例如Flash - 现在Javascript核心中有大量的web apis可供使用多媒体设备相对简单,并具有相当好的跨浏览器支持。

以下两个脚本(可以合并为一个)应该让您了解如何使用所述技术完成任务 - 将数据保存到数据库的部分使用prepared statement因此应该没有使用原始的,失败的代码可能会导致sql注入的重大风险。

<!--
    html5_snapshot.php
    ------------------
-->
<!DOCTYPE html>
<html>
    <head>
        <meta charset='utf-8'>
        <title>Webcam snapshots</title>
        <style>
            body{
                padding:3em;    
            }
            #media,
            #buttons,
            #results{
                box-sizing:border-box;
                width:80%;
                margin:1rem auto;
                float:none;
                text-align:center;
            }
            video,canvas{
                margin:2rem auto;
                border:1px solid black;
                border-radius:10px;
                display:inline-block;
                position:relative;
                float:none;
                clear:none;
                width:320px;
                height:240px;
            }
            h1{
                text-shadow: 1px 1px 2px black, 0 0 1em blue, 0 0 0.2em blue;
                color: white;
                width:80%;
                margin:0 auto 0 auto!important;
                float:none;
                font: 1.5em verdana;
                text-align:center;
            }
            #results{
                font-size:0.7rem;
            }
        </style>
        <script>
            window.addEventListener('DOMContentLoaded', function(e) {
                ( function() {
                    /* edit path to suit */
                    var handler='html5_snapshot_handler.php';
                    /* establish main variables */
                    var streaming   =   false,
                      oSave         =   document.getElementById('save'),
                      oClear        =   document.getElementById('clear'),
                      oGrab         =   document.getElementById('grab'),
                      video         =   document.getElementById('video'),
                      canvas        =   document.getElementById('canvas'),
                      width = 640,
                      height = 480;

                    var basicOptions={
                        video: true,
                        audio: false
                    };
                    /* callback for previous method-no longer used
                    function gotvideo(stream){
                        if( navigator.mozGetUserMedia ) {
                            video.mozSrcObject = stream;
                        } else {
                            var vendorURL = window.URL || window.webkitURL;
                            video.src = vendorURL.createObjectURL( stream );
                        }
                        video.play();
                    }
                    */
                    function report( msg ){
                        var ctx=canvas.getContext('2d');
                            ctx.font='2em verdana';
                            ctx.fillStyle='red';
                            ctx.textAlign='center'; 
                            ctx.textBaseline='middle';
                            ctx.fillText( msg, Math.abs( canvas.width * 0.5 ), Math.abs( canvas.height * 0.5 ) );
                        console.warn( msg );
                    }
                    function setproperties(e){
                        if( !streaming ) {
                            video.width=width;
                            video.height=height;
                            canvas.width=width;
                            canvas.height=height;
                            streaming = true;
                        }
                    }
                    function takepicture(e) {
                        e.preventDefault();
                        var ctx=canvas.getContext('2d');
                            ctx.drawImage( video, 0, 0, width, height );
                    }
                    function cbsaveimage( evt ){
                        /*
                            The ajax callback function - currently only shows 
                            the returned json data but could do something 
                            much more useful
                        */
                        document.getElementById('results').innerHTML=( this.status == 200 ) ? this.response : 'error: '+this.status;    
                    }
                    function saveimage(e){
                        var el=e.target;
                        var data=canvas.toDataURL('image/png').replace(/^data:image\/(png|jpg);base64,/, '');


                        if( !isBlankCanvas( canvas ) ){
                            var fd=new FormData();
                                fd.append( 'data', data );

                            var req = new XMLHttpRequest();
                                req.addEventListener('load', cbsaveimage, false );
                                req.open( 'POST', handler, true );
                                req.send( fd );

                        } else {
                            var bttns=[ oSave, oGrab, oClear ];

                            bttns.forEach( function(e,i,a){
                                e.disabled=true;
                            });
                            setTimeout( function(){
                                bttns.forEach( function(e,i,a){
                                    e.disabled=false;
                                });
                                canvas.getContext('2d').clearRect( 0,0, width, height );
                            },2500 );

                            report( 'Nothing to upload' );
                        }
                    }
                    function clearcanvas(evt){
                        canvas.getContext('2d').clearRect( 0,0, width, height );
                    }
                    function isBlankCanvas( canvas ) {
                        var blank=document.getElementById('empty');
                            blank.width=canvas.width;
                            blank.height=canvas.height;
                        return canvas.toDataURL() == blank.toDataURL();
                    }


                    /* Listeners */
                    oSave.addEventListener( 'click', saveimage, false );
                    oClear.addEventListener( 'click', clearcanvas, false );
                    oGrab.addEventListener( 'click', takepicture, false );
                    video.addEventListener( 'canplay', setproperties, false );

                    /*
                        navigator.getMedia = ( navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia );
                        navigator.getMedia( basicOptions, gotvideo, report );

                        The above method is deprecated ( still works in certain browsers however )
                        but neither the above or the newer method below will work in Internet Exploder
                        The below should work in Firefox,Chrome & Opera.

                    */

                    try{
                        navigator.mediaDevices.getUserMedia( basicOptions ) .then( function( stream ) {
                            video.srcObject = stream;
                            video.onloadedmetadata = function(e) {
                                video.play();
                            };
                        }).catch( function( err ) { console.log( err.name + ": " + err.message ); } );
                    }catch( error ){
                        console.log( error );
                    }

                })();
            },false );
        </script>
    </head>
    <body>
        <h1>Webcam snapshots</h1>
        <div id='media'>
            <video id='video'></video>
            <canvas id='canvas'></canvas>
            <canvas id='empty' style='display:none' width=100 height=100></canvas>
        </div>
        <div id='buttons'>
            <input type='button' id='grab' value='Take snapshot' />
            <input type='button' id='save' value='Save Snapshot' />
            <input type='button' id='clear' value='Clear canvas' />
        </div>
        <pre id='results'></pre>
    </body>
</html>


<?php
    /*

        html5_snapshot_handler.php
        --------------------------
    */

    session_start();

    if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['data'] ) ) {
        /* variable to register if db call is successful or not */
        $result=false;

        /* As the image does not have a name, create a name of some sort */
        $filename=uniqid('snapshot').'_'.time().'.png';

        /* The path on the server where the upload is to be stored. */
        $uploadpath='c:/temp/fileuploads/2/';

        /* Final path for uploaded image */
        $filepath=$uploadpath . $filename;

        /* Get the file "data" */
        $data = filter_input( INPUT_POST, 'data', FILTER_SANITIZE_SPECIAL_CHARS );

        /* write to a new file */
        $bytes = file_put_contents( $filepath, base64_decode( $data ) );

        /* Save to database */
        $dbhost =   'localhost';
        $dbuser =   'root'; 
        $dbpwd  =   'xxx'; 
        $dbname =   'stack';

        $db =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
        $sql='insert into `uploadimages` (`name`,`image`,`user_id`) values (?,?,?);';
        $stmt=$db->prepare( $sql );
        if( $stmt ){
            $stmt->bind_param('ssi', $name, $image, $uid );
            /*
                It would be wise to store just the path to the image
                as the file is being uploaded anyway so you do not need
                to store a BLOB - over time it would take up a huge 
                amount of diskspace on the database server
            */
            $name=$filename;
            $image=$filepath;
            $uid=$_SESSION['vid'];

            $result = $stmt->execute();
            $stmt->free_result();
            $stmt->close();
            $db->close();
        }

        /* send something back to the client - callback */
        header( 'Content-Type: application/json' );
        exit( json_encode( array(
            'filename'  =>  $filename,
            'filepath'  =>  $filepath,
            'filesize'  =>  $bytes,
            'status'    =>  realpath( $filepath ) ? 1 : 0,
            'db'        =>  $result
        ) ) );
    }


    /* If the request is other than POST - report an error */
    exit( header( 'HTTP/1.1 404 Not Found', true, 404 ) );

?>

承认失败的时间 - 我无法让上述工作与IE11一起工作(虽然我相信GithubwebRTC4allTemasys WebRTC可以使用填充,但我尝试过没有那些。我确定其他地方还会有其他的填充物。

早在90年代早期,当Internet Explorer在浏览器市场占据主导地位时,我们曾经喜欢编写IE,并且总是发现Netscape Navigator会抛出各种错误 - 现在虽然它是一个角色颠倒。