[JS] 使用 dropzone.js 實現多檔案上傳
〈1〉概述 DropzoneJS is an open source library that provides drag’n’drop file uploads with image previews. Dropzone.js is a light weight JavaScript library that turns an HTML element into a dropzone. This means that a user can drag and drop a file onto it, and the file gets uploaded to the server via AJAX. ☞ DropzoneJS 官方網站、中文版介紹
〈2〉上傳檔案 ☞ DEMO
1. Include the CSS Stylesheet.
2. Include DropzoneJS JavaScript library.
3. Create an upload form with css class "dropzone" and "action" is "upload.php".
注意! By default, DropzoneJS will find all forms with class "dropzone" and automatically attach itself to it. ☞ 教學文件:DropzoneJs + PHP: How to build a file upload form
簡單範例
〔下載我的範例〕資料結構
├── css/
│ └── dropzone.css
├── js/
│ └── dropzone.js
├── uploads (存放圖檔)
├── index.php (上傳介面)
└── upload.php (ajax 上傳圖檔)
index.php
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" /> <title>Demo Page</title> <link rel="stylesheet" href="css/dropzone.css" /> <script src="js/dropzone.js"></script> </head> <body> <div action="upload.php" class="dropzone"></div> </body> </html>
upload.php
<?php // 檔案存放路徑 $ds = DIRECTORY_SEPARATOR; $storeFolder = 'uploads'; $targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds; // 如果檔案不為空,則上傳 if (!empty($_FILES)) { $tempFile = $_FILES['file']['tmp_name']; $targetFile = $targetPath. $_FILES['file']['name']; if ( move_uploaded_file($tempFile,$targetFile) ) { echo "File is valid, and was successfully uploaded.\n"; } else { echo "Possible file upload attack!\n"; } echo "Here is some more debugging info:\n"; echo '<pre>'; print_r($_FILES); echo '</pre>'; } ?>
〈3〉刪除上傳的檔案 ☞ DEMO
☞ InfoTuts | Delete Uploaded file in Dropzone.Js
☞ how to upload and delete files from dropzone.js
☞ Dropzone.js Remove “Drop files here or click to upload.” when file is uploading
☞ Upload Delete from server MySQL, uploaded file in Dropzone.js using PHP
簡單範例
〔下載我的範例〕資料結構
├── css/
│ │── bootstrap.min.css
│ │── dropzone.css
│ │── dropzonejs.png
│ │── spritemap.png
│ └── spritemap@2x.png
├── js/
│ │── jquery_2.1.4.min.js
│ └── dropzone.js
├── uploads (存放圖檔)
├── database.php (連線資料庫)
├── delete.php (ajax 刪除圖檔)
├── index.php (上傳介面)
├── upload.php (ajax 上傳圖檔)
└── upload_get.php (ajax 顯示已上傳圖檔)
先建立好 Table
CREATE TABLE `myproducts` ( pid INT(11) NOT NULL AUTO_INCREMENT, product_name VARCHAR(100) NOT NULL, filename TEXT NOT NULL, isStop INT(1) NOT NULL, PRIMARY KEY (pid) ); ALTER TABLE `myproducts` CHANGE `isStop` `isStop` INT(1) NOT NULL DEFAULT '0';
準備好資料庫連線 database.php
<?php $hostname = 'localhost'; $username = 'user'; $password = ''; $db_name = 'test'; try{ $db = new PDO("mysql:host=".$hostname."; dbname=".$db_name, $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")); //PDO::MYSQL_ATTR_INIT_COMMAND 設定編碼 } catch(PDOException $e){ //error message echo $e->getMessage(); exit; } ?>
index.php
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" /> <title>Demo Page</title> <!-- Mainly css --> <link rel="stylesheet" href="css/bootstrap.min.css" /> <!-- DROPZONE --> <link rel="stylesheet" href="css/dropzone.css" /> </head> <body> <div class="container"> <div id="my-dropzone" class="dropzone"></div> </div> <!-- Mainly scripts --> <script src="js/jquery_2.1.4.min.js"></script> <!-- DROPZONE --> <script src="js/dropzone.js"></script> <script> $(document).ready(function(){ Dropzone.options.myDropzone = { // 一次上傳 uploadMultiple: true, // 文件提交頁面 url: "upload", // 限制檔案上傳數量 maxFiles: 10, // 限制檔案上傳大小,單位是 MB maxFilesize: 1, // 允許上傳的檔案類型 acceptedFiles: 'image/jpeg, image/png', // 翻譯選項 dictDefaultMessage : "將檔案拖放到這裡 (或這裡點擊)", dictFallbackMessage : "您的瀏覽器不支援拖放檔案上傳", dictFallbackText : "您的瀏覽器不支援拖放檔案上傳", dictFileTooBig : "檔案大小限制:{{maxFilesize}}MB, 檔案太大 ({{filesize}}MB)", dictInvalidFileType : "您可以上傳 jpg, jpeg, png 圖檔", dictCancelUpload : "取消上傳", dictCancelUploadConfirmation: "您確定取消上傳這張圖檔嗎?", dictRemoveFile : "刪除檔案", dictRemoveFileConfirmation : "您確定刪除這張圖檔嗎?", dictMaxFilesExceeded : "You can not upload any more files.", dictMaxFilesExceeded : "檔案個數限制:10", init: function() { var myDropzone = this; // Delete files this.on('removedfile', function(file) { var file_name = file.name; $.ajax({ type: 'POST', url: 'delete.php', data: { 'filename': file_name }, success: function(report) { console.log(report); }, error: function(report) { console.log(report); } }); }); //End Delete files //Added Code $.getJSON('upload_get.php', function(data) { // get the json response $.each(data, function(key,value){ //loop through it //想要傳輸的_POST value var mockFile = { name: value.name, size: value.size }; myDropzone.options.addedfile.call(myDropzone, mockFile); //放置檔案的路徑及檔名 myDropzone.options.thumbnail.call(myDropzone, mockFile, "uploads/"+value.name); }); }); //End added code } } }); </script> </body> </html>
upload.php
<?php include_once 'database.php'; // 檔案存放路徑 $ds = DIRECTORY_SEPARATOR; $storeFolder = 'uploads'; $targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds; // 如果檔案不為空,則上傳 if (!empty($_FILES)) { // 處理檔案原始名稱 $nameFile = $_FILES['file']['name']; $splitName = explode(".", $nameFile); // 產生檔案陣列 $nameNewFile = $splitName[0]; // $nameExe = end( $splitName ); // 檔案副檔名 // 處理暫存檔名稱 $tempFile = $_FILES['file']['tmp_name']; // 暫存檔資料夾位置 // $splitName = explode("\\", $tempFile); // 暫存檔陣列 // $tempNewFile = $splitName[4]; // $splitName = explode(".", $tempNewFile); // 暫存檔陣列 // $tempNewFile = $splitName[0].".".$nameExe; // 暫存檔名稱 // 新檔名上傳 $targetFile = $targetPath. $nameFile; if ( move_uploaded_file($tempFile, iconv("UTF-8", "big5", $targetFile) ) ) { // 寫入資料庫 try{ $sql = "INSERT INTO `myproducts` (product_name, filename) VALUES ('".$nameNewFile."', '".$nameFile."')"; // Prepare statement $db->exec($sql); } catch(PDOException $e) { echo $sql . "<br>" . $e->getMessage(); } } //echo "Here is some more debugging info:\n"; //echo '<pre>'; //print_r($_FILES); //echo '</pre>'; } ?>
delete.php
<?php include_once 'database.php'; // 刪除 if ($_SERVER["REQUEST_METHOD"] == "POST") { $filename = $_POST['filename']; // 檔案存放路徑 $upload_dir = 'uploads'; $targetPath = dirname( __FILE__ ) . DIRECTORY_SEPARATOR . $upload_dir . DIRECTORY_SEPARATOR; $targetFile = $targetPath. $filename; // 更新資料庫 try{ $sql = "UPDATE `myproducts` SET `isStop`=1 WHERE `filename`='".$filename."'"; // Prepare statement $stmt = $db->prepare($sql); // execute the query $stmt->execute(); } catch(PDOException $e) { echo $sql . "<br>" . $e->getMessage(); } // 刪除檔案 unlink( iconv("UTF-8", "big5", $targetFile) ); //print_r("Successfully deleted."); } ?>
upload_get.php
<?php include_once 'database.php'; $result = array(); try { $results = $db->prepare(" SELECT pid, product_name, filename FROM `myproducts` WHERE isStop = ?"); $results->bindValue(1, 0); $results->execute(); } catch (Exception $e) { echo "Data could not be retrieved from the database."; exit; } $arrValues = $results->fetchAll(PDO::FETCH_ASSOC); foreach ($arrValues as $row){ if($row['filename'] != ''){ $str = "".$row['filename'].""; $str = rtrim($str,','); $arr = explode(",",$str); // print_r($arr); foreach($arr as $file){ //get an array which has the names of all the files and loop through it $obj['name'] = $file; //get the filename in array $obj['size'] = filesize(iconv("UTF-8", "big5","uploads/".$file)); //get the flesize in array $result[] = $obj; // copy it to another array } } } // print_r($result); header('Content-Type: application/json'); echo json_encode($result); ?>
index.php
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" /> <title>Demo Page</title> <!-- Mainly css --> <link rel="stylesheet" href="css/bootstrap.min.css" /> <!-- DROPZONE --> <link rel="stylesheet" href="css/dropzone.css" /> </head> <body> <div class="container"> <div id="my-dropzone" class="dropzone"></div> <button type="submit" class="btn btn-primary pull-right">上傳檔案</button> </div> <!-- Mainly scripts --> <script src="js/jquery_2.1.4.min.js"></script> <!-- DROPZONE --> <script src="js/dropzone.js"></script> <script> $(document).ready(function(){ Dropzone.options.myDropzone = { // 不主動提交 autoProcessQueue: false, // 同時上傳多少文件 parallelUploads: 10, // 文件提交頁面 url: "upload", // 限制檔案上傳數量 maxFiles: 10, // 限制檔案上傳大小,單位是 MB maxFilesize: 1, // 允許上傳的檔案類型 acceptedFiles: 'image/jpeg, image/png', // 一次上傳 uploadMultiple: true, // 翻譯選項 dictDefaultMessage : "將檔案拖放到這裡 (或這裡點擊)", dictFallbackMessage : "您的瀏覽器不支援拖放檔案上傳", dictFallbackText : "您的瀏覽器不支援拖放檔案上傳", dictFileTooBig : "檔案大小限制:{{maxFilesize}}MB, 檔案太大 ({{filesize}}MB)", dictInvalidFileType : "您可以上傳 jpg, jpeg, png 圖檔", dictCancelUpload : "取消上傳", dictCancelUploadConfirmation: "您確定取消上傳這張圖檔嗎?", dictRemoveFile : "刪除檔案", dictRemoveFileConfirmation : "您確定刪除這張圖檔嗎?", dictMaxFilesExceeded : "檔案個數限制:10", // The setting up of the dropzone init: function() { var myDropzone = this; // upload files $("button[type=submit]").click(function (e) { e.preventDefault(); e.stopPropagation(); myDropzone.processQueue(); }); // end upload files } } }); </script> </body> </html>
upload.php
<?php if ( !empty($_FILES['file']) ) { $arr_file = reArrayFiles($_FILES['file']); echo "<pre>"; print_r($arr_file); echo "</pre>"; } function reArrayFiles(&$file_post) { $file_ary = array(); $file_count = count($file_post['name']); $file_keys = array_keys($file_post); for ($i=0; $i<$file_count; $i++) { foreach ($file_keys as $key) { $file_ary[$i][$key] = $file_post[$key][$i]; } } return $file_ary; } ?>
Source
☞ Uploading multiple files (轉格式)☞ Multiple File Upload in PHP using DropzoneJS – Drag and Drop (非自動上傳)
☞ Dropzone Accepted Files Issue
☞ JavaScript 的文件拖曳上傳套件 dropzone.js 介紹
☞ 15+ FREE HTML5 JQUERY UPLOAD FILE SCRIPTS EXAMPLE
☞ How to Build a File Upload Form with Express and Dropzone.js
Image Source
☞ UPLOAD AND RESIZE IMAGE USING DROPZONE.JS, JQUERY, AJAX AND PHP☞ AJAX FILE UPLOAD WITH DROPEZONEJS AND PAPERCLIP
沒有留言: