html5 多个文件上传_HTML5拖放多个文件上传器

html5 多个文件上传

HTML5 Drag and Drop Multiple File Uploader
HTML5 Drag and Drop Multiple File Uploader

HTML5 Drag and Drop Multiple File Uploader Our new article is going to tell you about HTML5 file upload. Yes, I explained basics of html5 file upload in the past (in one of our previous articles), but today I would like to give you another example, the better one. Now, you can just drag and drop your images (multiple images) in order to start uploading. Plus, the script displays overall progress (in percentage, plus – files left) and server response (without actual uploading). I am going to display progress at CANVAS element in realtime. And, at the last – our script can upload files not only into own server, but to another too (we can say, that this is cross-site uploader).

HTML5拖放多个文件上传器我们的新文章将向您介绍HTML5文件上传。 是的,我曾经在上一篇文章中解释过html5文件上传的基础知识,但今天我想给您举一个更好的例子。 现在,您只需拖放图像(多张图像)即可开始上传。 另外,该脚本显示总体进度(百分比,再加上–剩余文件)和服务器响应(不实际上传)。 我将在CANVAS元素上实时显示进度。 最后,我们的脚本不仅可以将文件上传到自己的服务器中,而且还可以上传到另一个服务器(可以说,这是跨站点的上传器)。

Here are our demo and downloadable package:

这是我们的演示和可下载的软件包:

现场演示

[sociallocker]

[社交储物柜]

打包下载

[/sociallocker]

[/ sociallocker]

Ok, download the sources and lets begin !

好的,下载资源并开始吧!

步骤1. HTML (Step 1. HTML)

As the first – html markup:

作为第一个– html标记:

index.html (index.html)

    <div class="container">
        <div class="contr"><h2>Drag and Drop your images to 'Drop Area' (up to 5 files at a time, size - under 256kb)</h2></div>
        <div class="upload_form_cont">
            <div id="dropArea">Drop Area</div>
            <div class="info">
                <div>Files left: <span id="count">0</span></div>
                <div>Destination url: <input id="url" value="https://www.script-tutorials.com/demos/257/upload.php"/></div>
                <h2>Result:</h2>
                <div id="result"></div>
                <canvas width="500" height="20"></canvas>
            </div>
        </div>
    </div>
    <script src="js/script.js"></script>

    <div class="container">
        <div class="contr"><h2>Drag and Drop your images to 'Drop Area' (up to 5 files at a time, size - under 256kb)</h2></div>
        <div class="upload_form_cont">
            <div id="dropArea">Drop Area</div>
            <div class="info">
                <div>Files left: <span id="count">0</span></div>
                <div>Destination url: <input id="url" value="https://www.script-tutorials.com/demos/257/upload.php"/></div>
                <h2>Result:</h2>
                <div id="result"></div>
                <canvas width="500" height="20"></canvas>
            </div>
        </div>
    </div>
    <script src="js/script.js"></script>

As you can see, it consists of several main elements: ‘Drop area’ at the left and ‘Info block’ at the right. When we drag and drop image files on our dropArea, in the Info block we will get response from server. Pay attention, that there is ‘Destination url’ element. Right now it connected to our server. But you can change it to your url anytime.

如您所见,它由几个主要元素组成:左侧为“拖放区域”,右侧为“信息块”。 当我们将图像文件拖放到dropArea上时,在Info块中,我们将获得服务器的响应。 请注意,有“目标网址”元素。 现在,它已连接到我们的服务器。 但是您可以随时将其更改为您的网址。

步骤2. CSS (Step 2. CSS)

css / main.css (css/main.css)

Now, its time to customize our layout:

现在,是时候自定义布局了:

css / main.css (css/main.css)

.container {
    overflow:hidden;
    width:960px;
    margin:20px auto;
}
.contr {
    background-color: #212121;
    color: #FFFFFF;
    padding: 10px 0;
    text-align: center;
    border-radius:10px 10px 0 0;
    -moz-border-radius:10px 10px 0 0;
    -webkit-border-radius:10px 10px 0 0;
}
.upload_form_cont {
    background: -moz-linear-gradient(#ffffff, #f2f2f2);
    background: -ms-linear-gradient(#ffffff, #f2f2f2);
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #ffffff), color-stop(100%, #f2f2f2));
    background: -webkit-linear-gradient(#ffffff, #f2f2f2);
    background: -o-linear-gradient(#ffffff, #f2f2f2);
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#f2f2f2');
    -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#f2f2f2')";
    background: linear-gradient(#ffffff, #f2f2f2);
    color: #000;
    overflow: hidden;
}
.info {
    background-color: #EEEEEE;
    border: 1px solid #DDDDDD;
    float: left;
    font-weight: bold;
    height: 530px;
    margin: 20px;
    position: relative;
    width: 560px;
}
.info > div {
    font-size: 14px;
    font-weight: bold;
    padding: 10px 15px 5px;
}
.info > h2 {
    padding: 0 15px;
}
.info > canvas {
    margin-left: 15px;
    margin-bottom: 10px;
}
.info #url {
    width: 400px;
}
#dropArea {
    background-color: #DDDDDD;
    border: 3px dashed #000000;
    float: left;
    font-size: 48px;
    font-weight: bold;
    height: 530px;
    line-height: 530px;
    margin: 20px;
    position: relative;
    text-align: center;
    width: 300px;
}
#dropArea.hover {
    background-color: #CCCCCC;
}
#dropArea.uploading {
    background: #EEEEEE url(loading.gif) center 30% no-repeat;
}
#result .s, #result .f {
    font-size: 12px;
    margin-bottom: 10px;
    padding: 10px;
    border-radius:10px;
    -moz-border-radius:10px;
    -webkit-border-radius:10px;
}
#result .s {
    background-color: #77fc9f;
}
#result .f {
    background-color: #fcc577;
}

.container {
    overflow:hidden;
    width:960px;
    margin:20px auto;
}
.contr {
    background-color: #212121;
    color: #FFFFFF;
    padding: 10px 0;
    text-align: center;
    border-radius:10px 10px 0 0;
    -moz-border-radius:10px 10px 0 0;
    -webkit-border-radius:10px 10px 0 0;
}
.upload_form_cont {
    background: -moz-linear-gradient(#ffffff, #f2f2f2);
    background: -ms-linear-gradient(#ffffff, #f2f2f2);
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #ffffff), color-stop(100%, #f2f2f2));
    background: -webkit-linear-gradient(#ffffff, #f2f2f2);
    background: -o-linear-gradient(#ffffff, #f2f2f2);
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#f2f2f2');
    -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#f2f2f2')";
    background: linear-gradient(#ffffff, #f2f2f2);
    color: #000;
    overflow: hidden;
}
.info {
    background-color: #EEEEEE;
    border: 1px solid #DDDDDD;
    float: left;
    font-weight: bold;
    height: 530px;
    margin: 20px;
    position: relative;
    width: 560px;
}
.info > div {
    font-size: 14px;
    font-weight: bold;
    padding: 10px 15px 5px;
}
.info > h2 {
    padding: 0 15px;
}
.info > canvas {
    margin-left: 15px;
    margin-bottom: 10px;
}
.info #url {
    width: 400px;
}
#dropArea {
    background-color: #DDDDDD;
    border: 3px dashed #000000;
    float: left;
    font-size: 48px;
    font-weight: bold;
    height: 530px;
    line-height: 530px;
    margin: 20px;
    position: relative;
    text-align: center;
    width: 300px;
}
#dropArea.hover {
    background-color: #CCCCCC;
}
#dropArea.uploading {
    background: #EEEEEE url(loading.gif) center 30% no-repeat;
}
#result .s, #result .f {
    font-size: 12px;
    margin-bottom: 10px;
    padding: 10px;
    border-radius:10px;
    -moz-border-radius:10px;
    -webkit-border-radius:10px;
}
#result .s {
    background-color: #77fc9f;
}
#result .f {
    background-color: #fcc577;
}

步骤3. HTML5 JS (Step 3. HTML5 JS)

js / script.js (js/script.js)

// variables
var dropArea = document.getElementById('dropArea');
var canvas = document.querySelector('canvas');
var context = canvas.getContext('2d');
var count = document.getElementById('count');
var destinationUrl = document.getElementById('url');
var result = document.getElementById('result');
var list = [];
var totalSize = 0;
var totalProgress = 0;
// main initialization
(function(){
    // init handlers
    function initHandlers() {
        dropArea.addEventListener('drop', handleDrop, false);
        dropArea.addEventListener('dragover', handleDragOver, false);
    }
    // draw progress
    function drawProgress(progress) {
        context.clearRect(0, 0, canvas.width, canvas.height); // clear context
        context.beginPath();
        context.strokeStyle = '#4B9500';
        context.fillStyle = '#4B9500';
        context.fillRect(0, 0, progress * 500, 20);
        context.closePath();
        // draw progress (as text)
        context.font = '16px Verdana';
        context.fillStyle = '#000';
        context.fillText('Progress: ' + Math.floor(progress*100) + '%', 50, 15);
    }
    // drag over
    function handleDragOver(event) {
        event.stopPropagation();
        event.preventDefault();
        dropArea.className = 'hover';
    }
    // drag drop
    function handleDrop(event) {
        event.stopPropagation();
        event.preventDefault();
        processFiles(event.dataTransfer.files);
    }
    // process bunch of files
    function processFiles(filelist) {
        if (!filelist || !filelist.length || list.length) return;
        totalSize = 0;
        totalProgress = 0;
        result.textContent = '';
        for (var i = 0; i < filelist.length && i < 5; i++) {
            list.push(filelist[i]);
            totalSize += filelist[i].size;
        }
        uploadNext();
    }
    // on complete - start next file
    function handleComplete(size) {
        totalProgress += size;
        drawProgress(totalProgress / totalSize);
        uploadNext();
    }
    // update progress
    function handleProgress(event) {
        var progress = totalProgress + event.loaded;
        drawProgress(progress / totalSize);
    }
    // upload file
    function uploadFile(file, status) {
        // prepare XMLHttpRequest
        var xhr = new XMLHttpRequest();
        xhr.open('POST', destinationUrl.value);
        xhr.onload = function() {
            result.innerHTML += this.responseText;
            handleComplete(file.size);
        };
        xhr.onerror = function() {
            result.textContent = this.responseText;
            handleComplete(file.size);
        };
        xhr.upload.onprogress = function(event) {
            handleProgress(event);
        }
        xhr.upload.onloadstart = function(event) {
        }
        // prepare FormData
        var formData = new FormData();
        formData.append('myfile', file);
        xhr.send(formData);
    }
    // upload next file
    function uploadNext() {
        if (list.length) {
            count.textContent = list.length - 1;
            dropArea.className = 'uploading';
            var nextFile = list.shift();
            if (nextFile.size >= 262144) { // 256kb
                result.innerHTML += '<div class="f">Too big file (max filesize exceeded)</div>';
                handleComplete(nextFile.size);
            } else {
                uploadFile(nextFile, status);
            }
        } else {
            dropArea.className = '';
        }
    }
    initHandlers();
})();

// variables
var dropArea = document.getElementById('dropArea');
var canvas = document.querySelector('canvas');
var context = canvas.getContext('2d');
var count = document.getElementById('count');
var destinationUrl = document.getElementById('url');
var result = document.getElementById('result');
var list = [];
var totalSize = 0;
var totalProgress = 0;
// main initialization
(function(){
    // init handlers
    function initHandlers() {
        dropArea.addEventListener('drop', handleDrop, false);
        dropArea.addEventListener('dragover', handleDragOver, false);
    }
    // draw progress
    function drawProgress(progress) {
        context.clearRect(0, 0, canvas.width, canvas.height); // clear context
        context.beginPath();
        context.strokeStyle = '#4B9500';
        context.fillStyle = '#4B9500';
        context.fillRect(0, 0, progress * 500, 20);
        context.closePath();
        // draw progress (as text)
        context.font = '16px Verdana';
        context.fillStyle = '#000';
        context.fillText('Progress: ' + Math.floor(progress*100) + '%', 50, 15);
    }
    // drag over
    function handleDragOver(event) {
        event.stopPropagation();
        event.preventDefault();
        dropArea.className = 'hover';
    }
    // drag drop
    function handleDrop(event) {
        event.stopPropagation();
        event.preventDefault();
        processFiles(event.dataTransfer.files);
    }
    // process bunch of files
    function processFiles(filelist) {
        if (!filelist || !filelist.length || list.length) return;
        totalSize = 0;
        totalProgress = 0;
        result.textContent = '';
        for (var i = 0; i < filelist.length && i < 5; i++) {
            list.push(filelist[i]);
            totalSize += filelist[i].size;
        }
        uploadNext();
    }
    // on complete - start next file
    function handleComplete(size) {
        totalProgress += size;
        drawProgress(totalProgress / totalSize);
        uploadNext();
    }
    // update progress
    function handleProgress(event) {
        var progress = totalProgress + event.loaded;
        drawProgress(progress / totalSize);
    }
    // upload file
    function uploadFile(file, status) {
        // prepare XMLHttpRequest
        var xhr = new XMLHttpRequest();
        xhr.open('POST', destinationUrl.value);
        xhr.onload = function() {
            result.innerHTML += this.responseText;
            handleComplete(file.size);
        };
        xhr.onerror = function() {
            result.textContent = this.responseText;
            handleComplete(file.size);
        };
        xhr.upload.onprogress = function(event) {
            handleProgress(event);
        }
        xhr.upload.onloadstart = function(event) {
        }
        // prepare FormData
        var formData = new FormData();
        formData.append('myfile', file);
        xhr.send(formData);
    }
    // upload next file
    function uploadNext() {
        if (list.length) {
            count.textContent = list.length - 1;
            dropArea.className = 'uploading';
            var nextFile = list.shift();
            if (nextFile.size >= 262144) { // 256kb
                result.innerHTML += '<div class="f">Too big file (max filesize exceeded)</div>';
                handleComplete(nextFile.size);
            } else {
                uploadFile(nextFile, status);
            }
        } else {
            dropArea.className = '';
        }
    }
    initHandlers();
})();

Most of code is already commented. I hope that you can understand all this code. Anyway – some explanation how it works: in the beginning, we have linked two handlers to our DropArea: ‘drop’ and ‘dropover’. When we keep our dragged files over our Drop area, we can apply custom styles to our drop area. Then, when we drop our files, our script starts executing ‘processFiles’ function (it pushs all the dropped files into array, and starts uploading them step by step). In the result, we send data through XMLHttpRequest object to custom recipient server. During sending the files, we also display overall progress at our canvas element.

大多数代码已被注释。 希望您能理解所有这些代码。 无论如何-一些解释它是如何工作的:一开始,我们已经将两个处理程序链接到我们的DropArea:“ drop”和“ dropover”。 当我们将拖动的文件保留在放置区域上时,可以将自定义样式应用于放置区域。 然后,当我们删除文件时,脚本开始执行'processFiles'函数(它将所有删除的文件推送到数组中,并开始逐步上载它们)。 结果,我们通过XMLHttpRequest对象将数据发送到自定义收件人服务器。 在发送文件期间,我们还将在canvas元素上显示总体进度。

步骤4. PHP (Step 4. PHP)

upload.php (upload.php)

<?php
// set error reporting level
if (version_compare(phpversion(), '5.3.0', '>=') == 1)
  error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
else
  error_reporting(E_ALL & ~E_NOTICE);
function bytesToSize1024($bytes, $precision = 2) {
    $unit = array('B','KB','MB');
    return @round($bytes / pow(1024, ($i = floor(log($bytes, 1024)))), $precision).' '.$unit[$i];
}
if (isset($_FILES['myfile'])) {
    $sFileName = $_FILES['myfile']['name'];
    $sFileType = $_FILES['myfile']['type'];
    $sFileSize = bytesToSize1024($_FILES['myfile']['size'], 1);
    echo <<<EOF
<div class="s">
    <p>Your file: {$sFileName} has been successfully received.</p>
    <p>Type: {$sFileType}</p>
    <p>Size: {$sFileSize}</p>
</div>
EOF;
} else {
    echo '<div class="f">An error occurred</div>';
}

<?php
// set error reporting level
if (version_compare(phpversion(), '5.3.0', '>=') == 1)
  error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
else
  error_reporting(E_ALL & ~E_NOTICE);
function bytesToSize1024($bytes, $precision = 2) {
    $unit = array('B','KB','MB');
    return @round($bytes / pow(1024, ($i = floor(log($bytes, 1024)))), $precision).' '.$unit[$i];
}
if (isset($_FILES['myfile'])) {
    $sFileName = $_FILES['myfile']['name'];
    $sFileType = $_FILES['myfile']['type'];
    $sFileSize = bytesToSize1024($_FILES['myfile']['size'], 1);
    echo <<<EOF
<div class="s">
    <p>Your file: {$sFileName} has been successfully received.</p>
    <p>Type: {$sFileType}</p>
    <p>Size: {$sFileSize}</p>
</div>
EOF;
} else {
    echo '<div class="f">An error occurred</div>';
}

Its server-side file. It doesn’t upload files of course. But it returns some information about our files (which we will display at our receiver (client) side).

它的服务器端文件。 当然,它不会上传文件。 但是它返回一些有关文件的信息(我们将在接收方(客户端)显示这些信息)。

现场演示

结论 (Conclusion)

Hope this helped to you! Welcome back to read our new articles about HTML5. Good luck!

希望这对您有所帮助! 欢迎回来阅读我们有关HTML5的新文章。 祝好运!

翻译自: https://www.script-tutorials.com/html5-drag-and-drop-multiple-file-uploader/

html5 多个文件上传

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值