HTML5 drag & drop upload

html5 drag drop upload example

ตัวอย่างในบทความนี้นำ jquery html5 upload plugin มาจาก http://timc.idv.tw/html5-file-upload/

ใน html 5 จะมีคำสั่งใน javascript ที่ให้สามารถรองรับการลากแล้ววางเพื่อทำการอัพโหลดได้ แต่การเขียนแบบพื้นๆมันก็ยากพอสมควร การหา plugin ของ javascript framework อย่าง jquery มาใช้มันทำให้ทุกอย่างง่ายขึ้น

การอัพโหลดด้วยวิธีนี้ เบราเซอร์จะต้องเป็นรุ่นใหม่ที่รองรับการทำงานเท่านั้น และมันสามารถทำ ajax upload ได้ ซึ่งปกติแล้วมันไม่สามารถทำได้เลย เราจึงเห็น flash upload อย่าง uploadify มาทำงานแทนที่

ตัวอย่างการเขียนฟอร์มสำหรับอัพโหลด


<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>html5 upload</title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
        <script type="text/javascript" src="jquery.html5-fileupload.js"></script>
        
        <style type="text/css">
            body, * {font-size: 12px;}
            h1 {font-size: 20px; margin: 5px 0;}
            .container {border: thin solid #ccc; display: block; margin: 50px auto 0 auto; padding: 10px; width: 900px;}
            .container form {background: #f5f5f5; padding: 10px;}
            
            .block-error {background: #fff5f5; border: 3px solid #ff6767; color: #f00; font-weight: bold;}
            .block-success {background: lightgreen; border: 3px solid darkgreen; font-weight: bold;}
            
            .result_img {max-width: 900px;}
            
            #dropbox {border: 3px dashed #ccc; margin: 10px; min-height: 100px; padding: 10px;}
        </style>
    </head>
    <body>
        
        <div class="container">
            <h1>HTML5 drag &amp; drop upload</h1>
            <div class="result"></div>
            <div id="detector"></div>
            <form method="post" action="dd-upload.json.php" enctype="multipart/form-data">
                <?php if ( isset($form_status) ) {echo $form_status;} ?>
                <input type="hidden" name="MAX_FILE_SIZE" value="2097152" /><!--2097152 byte = 2MB -->
                File browse:<input type="file" name="Filedata" value="" class="file-upload" /><br />
                OR drag and drop file here:
                <div id="dropbox"></div>
                <button type="submit" name="btn" value="upload" onclick="return false;">Upload</button>
            </form>
        </div>
        <script type="text/javascript">
        $(document).ready(function() {
            if (!$.fileUploadSupported) {
                $('#detector').addClass("block-error");
                $('#detector').text('This browser is NOT supported.');
            }
            
            $('.file-upload, #dropbox').fileUpload({
                url: 'dd-upload.json.php',
                type: 'POST',
                dataType: 'json',
                beforeSend: function () {
                    $(document.body).addClass('uploading');
                },
                complete: function () {
                    $(document.body).removeClass('uploading');
                },
                success: function (result, status, xhr) {
                    if (!result) {
                        window.alert('Server error.');
                        return;
                    }
                    if (result.error !== 0) {
                        window.alert(result.error);
                        return;
                    }
                    $(".result").html("Uploaded result:<br /><img src=\""+result.file_name+"\" alt=\"img\" class=\"result_img\" />");
                    window.alert('Success! You have sent a file named \'' + result.file_name + '\' with MIME type \'' + result.file_type + '\'.');
                }
            });
        });// jquery document ready
        </script>
        
    </body>
</html>


file dd-upload.php (drag & drop upload)
ในไฟล์นี้มีทั้ง select upload ธรรมดา และ div box สำหรับลากและวางไฟล์ลงในนั้นเพื่ออัพโหลด

 

ตัวอย่างการเขียน php สำหรับทำการอัพโหลด

ในส่วนของไฟล์ที่ทำการอัพโหลดจะมีวิธีเขียนที่แปลกสักหน่อย โดยผลลัพธ์จะต้องเป็น json encode และ content type javascript ดังตัวอย่าง


header('Content-Type: text/javascript');

require("vfileup.php");

if ( isset($_FILES['Filedata']['name']) && $_FILES['Filedata']['name'] != null ) {
    /*print(
        json_encode(
            array_merge(
                $_FILES['Filedata'],
                array( 'getimagesize' => getimagesize($_FILES['Filedata']['tmp_name']) )
            )
        )
    ); exit;*/
    // result from above.
    // {"name":"0001.jpg","type":"image\/jpeg","tmp_name":"C:\\Windows\\Temp\\phpF7C7.tmp","error":0,"size":402239,"getimagesize":{"0":1430,"1":600,"2":2,"3":"width=\"1430\" height=\"600\"","bits":8,"channels":3,"mime":"image\/jpeg"}}
    //
    $vfileup = new vfileup($_FILES['Filedata']);
    $vfileup->allowed_types = "jpg|gif|png";
    $vfileup->overwrite = true;
    $vfileup->upload_path = dirname(__FILE__);
    // upload
    $upload_result = $vfileup->do_upload();
    if ( $upload_result !== true ) {
        echo json_encode(array("error" => $vfileup->error_msg));
    } else {
        //echo json_encode("อัพโหลดสำเร็จ");
        $data = $vfileup->data();
        $data['error'] = 0;// required must be 0 NOT false or "0" or '0'.
        echo json_encode($data);
        // result from above
        // {"file_name":"0000.jpg","file_name_only":"0000","file_type":"image\/jpeg","file_path":"C:\\my sites\\test\\html5-upload\\0000.jpg","full_path":"C:\\my sites\\test\\html5-upload","orig_name":"0000.jpg","client_name":"0000.jpg","file_ext":"jpg","file_size":493625,"error":0}
        
    }
} else {
    echo json_encode(array("error" => "please select a file."));
}


file dd-upload.json.php

ในไฟล์นี้จะใช้ vfileup upload class มาทำการช่วยในการอัพโหลดให้ง่ายขึ้น

ข้อเสียของ jquery plugin ตัวนี้คือ การส่งค่า input name สำหรับไฟล์จะเป็น Filedata เท่านั้นเนื่องจากถูกกำหนดอยู่ในไฟล์ .js เรียบร้อยเลย แต่ก็ยังมี plug in อื่นๆที่ทำงานได้เหมือนกันให้เลือกใช้อีกหลายตัว ในตัวอย่างนี้จึงทำให้เห็นถึงการใช้งานจริงและสำหรับศึกษา, นำไปปรับแต่งเท่านั้น

ดาวน์โหลดตัวอย่างเต็มสำหรับบทความนี้

ดาวน์โหลด

ใส่ความเห็น

อีเมลของคุณจะไม่แสดงให้คนอื่นเห็น ช่องข้อมูลจำเป็นถูกทำเครื่องหมาย *

คุณอาจใช้แท็กHTMLและแอททริบิวต์เหล่านี้: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>