搜尋
首頁後端開發php教程Laravel 5.1 中基于 Dropzone.js 实现图片拖拽上传及删除功能

注:本教程代码适用于Laravel 5.1版本。

1、概述

Dropzone 是目前最好的免费文件拖拽上传库,它拥有很多特性和选项以便你可以使用多种方式来自定义。

在Laravel项目集成Dropzone对没有经验的新手来说有点棘手,所以接下来我想你给你们展示最优雅的解决方案。

这篇教程将包括以下内容:

  • 自动 图片 上传
  • 通过Ajax请求从Dropzone预览中直接移除图片
  • 上传图片计数器
  • 保存完整尺寸图片和图标尺寸版本
  • 使用Intervention Image包调整图片尺寸和编码
  • 保存图片数据到数据库
  • 在服务器端生成唯一的图片名称

如果你还需要上传或裁剪图片,请参考上一篇教程: 在 Laravel 5 中使用 jQuery 插件 Croppic + Intervention Image 实现图片上传和裁剪 。

本教程的完整代码已公开在GitHub上: https://github.com/codingo-me/dropzone-laravel-image-upload

最终演示效果图如下:

2、项目基本配置

这里我们安装一个新的Laravel应用并创建包含数据库凭证信息的.env文件。

此外我们还要从 https://github.com/enyo/dropzone/tree/master/dist 下载样式和脚本文件,这些文件存放到 public/packages/dropzone 。

前端我们还是使用Bootstrap,相关文件存放在 public/packages/bootstrap 。

上面已经提到我们要使用Intervention Image扩展包来处理上传图片,并且这里我们会在Blade模板中用到html辅助函数,所以我们需要安装相关依赖,安装Intervention Image请参考: 在 Laravel 5 中集成 Intervention Image 实现对图片的创建、修改和压缩处理 ,而安装html请参考: Laravel 5 中使用 HtmlBuilder 及 URL::asset() 引入站内或站外的 css 和 js 文件 。

3、视图

本教程只包含单个页面用于上传图片,尽管这样我还是喜欢将布局和具体实现页面分开,我们编辑布局文件 layout.blade.php 如下:

<!DOCTYPE html><html lang="en"><head>    <meta charset="utf-8">    <title>Image upload in Laravel 5.1 with Dropzone.js</title>    <meta name="viewport" content="width=device-width, initial-scale=1.0">    {!! HTML::style('/packages/bootstrap/css/bootstrap.min.css') !!}    {!! HTML::style('/assets/css/style.css') !!}    {!! HTML::script('https://code.jquery.com/jquery-2.1.4.min.js') !!}    @yield('head')</head><body><div class="container">    <div class="navbar navbar-default">        <div class="navbar-header">            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">                <span class="icon-bar"></span>                <span class="icon-bar"></span>                <span class="icon-bar"></span>            </button>            <a class="navbar-brand" href="/">Dropzone + Laravel</a>        </div>        <div class="navbar-collapse collapse">            <ul class="nav navbar-nav">                <li><a href="/">Upload</a></li>            </ul>        </div>    </div>    <br><br>@yield('content')</div></body>@yield('footer')</html>

接下来我们创建上传图片的视图文件 pages/upload.blade.php :

@extends('layout')@section('head')    {!! HTML::style('/packages/dropzone/dropzone.css') !!}@stop@section('footer')    {!! HTML::script('/packages/dropzone/dropzone.js') !!}    {!! HTML::script('/assets/js/dropzone-config.js') !!}@stop@section('content')    <div class="row">        <div class="col-md-offset-1 col-md-10">            <div class="jumbotron how-to-create" >                <h3 id="Images-span-id-photoCounter-span">Images <span id="photoCounter"></span></h3>                <br />                {!! Form::open(['url' => route('upload-post'), 'class' => 'dropzone', 'files'=>true, 'id'=>'real-dropzone']) !!}                <div class="dz-message">                </div>                <div class="fallback">                    <input name="file" type="file" multiple />                </div>                <div class="dropzone-previews" id="dropzonePreview"></div>                <h4 id="Drop-images-in-this-area-span-class-glyphicon-glyphicon-hand-down-span">Drop images in this area  <span class="glyphicon glyphicon-hand-down"></span></h4>                {!! Form::close() !!}            </div>            <div class="jumbotron how-to-create">                <ul>                    <li>Images are uploaded as soon as you drop them</li>                    <li>Maximum allowed size of image is 8MB</li>                </ul>            </div>        </div>    </div>    <!-- Dropzone Preview Template -->    <div id="preview-template" style="display: none;">        <div class="dz-preview dz-file-preview">            <div class="dz-image"><img  data-dz-thumbnail="" alt="Laravel 5.1 中基于 Dropzone.js 实现图片拖拽上传及删除功能" ></div>            <div class="dz-details">                <div class="dz-size"><span data-dz-size=""></span></div>                <div class="dz-filename"><span data-dz-name=""></span></div>            </div>            <div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress=""></span></div>            <div class="dz-error-message"><span data-dz-errormessage=""></span></div>            <div class="dz-success-mark">                <svg width="54px" height="54px" viewBox="0 0 54 54" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:sketch="http://www.bohemiancoding.com/sketch/ns">                    <!-- Generator: Sketch 3.2.1 (9971) - http://www.bohemiancoding.com/sketch -->                    <title>Check</title>                    <desc>Created with Sketch.</desc>                    <defs></defs>                    <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" sketch:type="MSPage">                        <path d="M23.5,31.8431458 L17.5852419,25.9283877 C16.0248253,24.3679711 13.4910294,24.366835 11.9289322,25.9289322 C10.3700136,27.4878508 10.3665912,30.0234455 11.9283877,31.5852419 L20.4147581,40.0716123 C20.5133999,40.1702541 20.6159315,40.2626649 20.7218615,40.3488435 C22.2835669,41.8725651 24.794234,41.8626202 26.3461564,40.3106978 L43.3106978,23.3461564 C44.8771021,21.7797521 44.8758057,19.2483887 43.3137085,17.6862915 C41.7547899,16.1273729 39.2176035,16.1255422 37.6538436,17.6893022 L23.5,31.8431458 Z M27,53 C41.3594035,53 53,41.3594035 53,27 C53,12.6405965 41.3594035,1 27,1 C12.6405965,1 1,12.6405965 1,27 C1,41.3594035 12.6405965,53 27,53 Z" id="Oval-2" stroke-opacity="0.198794158" stroke="#747474" fill-opacity="0.816519475" fill="#FFFFFF" sketch:type="MSShapeGroup"></path>                    </g>                </svg>            </div>            <div class="dz-error-mark">                <svg width="54px" height="54px" viewBox="0 0 54 54" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:sketch="http://www.bohemiancoding.com/sketch/ns">                    <!-- Generator: Sketch 3.2.1 (9971) - http://www.bohemiancoding.com/sketch -->                    <title>error</title>                    <desc>Created with Sketch.</desc>                    <defs></defs>                    <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" sketch:type="MSPage">                        <g id="Check-+-Oval-2" sketch:type="MSLayerGroup" stroke="#747474" stroke-opacity="0.198794158" fill="#FFFFFF" fill-opacity="0.816519475">                            <path d="M32.6568542,29 L38.3106978,23.3461564 C39.8771021,21.7797521 39.8758057,19.2483887 38.3137085,17.6862915 C36.7547899,16.1273729 34.2176035,16.1255422 32.6538436,17.6893022 L27,23.3431458 L21.3461564,17.6893022 C19.7823965,16.1255422 17.2452101,16.1273729 15.6862915,17.6862915 C14.1241943,19.2483887 14.1228979,21.7797521 15.6893022,23.3461564 L21.3431458,29 L15.6893022,34.6538436 C14.1228979,36.2202479 14.1241943,38.7516113 15.6862915,40.3137085 C17.2452101,41.8726271 19.7823965,41.8744578 21.3461564,40.3106978 L27,34.6568542 L32.6538436,40.3106978 C34.2176035,41.8744578 36.7547899,41.8726271 38.3137085,40.3137085 C39.8758057,38.7516113 39.8771021,36.2202479 38.3106978,34.6538436 L32.6568542,29 Z M27,53 C41.3594035,53 53,41.3594035 53,27 C53,12.6405965 41.3594035,1 27,1 C12.6405965,1 1,12.6405965 1,27 C1,41.3594035 12.6405965,53 27,53 Z" id="Oval-2" sketch:type="MSShapeGroup"></path>                        </g>                    </g>                </svg>            </div>        </div>    </div>    <!-- End Dropzone Preview Template -->@stop

在上传视图的 head 部分我们引入了Dropzone的默认样式,在 footer 部分我们传递默认的JavaScript文件以及我们自己的Dropzone配置文件。

内容部分包含两个部分,首先是上传表单然后是隐藏的图片预览区域,我是从Dropzone官网下载的预览模板代码,在配置文件中使用这个模板告诉Dropzone哪段HTML用于上传图片预览。

4、Dropzone配置

查看完整的Dropzone配置项列表参考 这里 ,对本项目来说我想从Dropzone一个一个上传文件,因为这样的话我就不需要循环遍历文件上传,并行上传文件数限制为100并且每个文件大小不能超过8M。

每个图片预览都对应一个删除链接,点击该链接Dropzone就会触发 removedfile 事件,该事件会创建上传/删除的Ajax请求,如果响应状态码是200,则对应图片计数器减少。

var photo_counter = 0;Dropzone.options.realDropzone = {    uploadMultiple: false,    parallelUploads: 100,    maxFilesize: 8,    previewsContainer: '#dropzonePreview',    previewTemplate: document.querySelector('#preview-template').innerHTML,    addRemoveLinks: true,    dictRemoveFile: 'Remove',    dictFileTooBig: 'Image is bigger than 8MB',    // The setting up of the dropzone    init:function() {        this.on("removedfile", function(file) {            $.ajax({                type: 'POST',                url: 'upload/delete',                data: {id: file.name},                dataType: 'html',                success: function(data){                    var rep = JSON.parse(data);                    if(rep.code == 200)                    {                        photo_counter--;                        $("#photoCounter").text( "(" + photo_counter + ")");                    }                }            });        } );    },    error: function(file, response) {        if($.type(response) === "string")            var message = response; //dropzone sends it's own error messages in string        else            var message = response.message;        file.previewElement.classList.add("dz-error");        _ref = file.previewElement.querySelectorAll("[data-dz-errormessage]");        _results = [];        for (_i = 0, _len = _ref.length; _i < _len; _i++) {            node = _ref[_i];            _results.push(node.textContent = message);        }        return _results;    },    success: function(file,done) {        photo_counter++;        $("#photoCounter").text( "(" + photo_counter + ")");    }}

该配置文件底部如果上传成功图片计数器增加。

5、上传逻辑

我习惯将特定逻辑放到Repository类,在本项目中我使用 ImageRepository 这个类,该类存放在 app/Logic/Image/ImageRepository.php 。

目前这个类只做两件事,上传单个文件以及删除指定文件,我们将整个Repository类注入到 ImageController 中:

<?phpnamespace App\Http\Controllers;use App\Logic\Image\ImageRepository;use Illuminate\Support\Facades\Input;class ImageController extends Controller{    protected $image;    public function __construct(ImageRepository $imageRepository)    {        $this->image = $imageRepository;    }    public function getUpload()    {        return view('pages.upload');    }    public function postUpload()    {        $photo = Input::all();        $response = $this->image->upload($photo);        return $response;    }    public function deleteUpload()    {        $filename = Input::get('id');        if(!$filename)        {            return 0;        }        $response = $this->image->delete( $filename );        return $response;    }}

因此对这个控制器而言我需要三个路由:显示上传表单,上传以及删除请求:

Route::get('/', ['as' => 'upload', 'uses' => 'ImageController@getUpload']);Route::post('upload', ['as' => 'upload-post', 'uses' =>'ImageController@postUpload']);Route::post('upload/delete', ['as' => 'upload-remove', 'uses' =>'ImageController@deleteUpload']);

ImageController 的 postUpload 方法将用户上传请求转发到 ImageRepository 类对应的 upload 方法。这个 upload 方法首先会验证输入,然后为上传文件分配唯一的文件名,再然后保存原始尺寸图片到指定目录,同时将图标尺寸图片保存到其它目录,此外还要保存到数据库以便Laravel可以跟踪图片上传记录。为此我们需要创建迁移文件并运行迁移命令:

<?phpuse Illuminate\Database\Schema\Blueprint;use Illuminate\Database\Migrations\Migration;class CreateImages extends Migration{    /**     * Run the migrations.     *     * @return void     */    public function up()    {        Schema::create('images', function (Blueprint $table) {            $table->increments('id');            $table->text('original_name');            $table->text('filename');            $table->timestamps();        });    }    /**     * Reverse the migrations.     *     * @return void     */    public function down()    {        Schema::drop('images');    }}

我已经提过了上传文件将会保存为两种尺寸,此外可能还要生成缩略图并对图片编码,要实现这些功能,我们需要使用Intervention Image扩展包:

<?phpnamespace App\Logic\Image;use App\Models\Image;use Illuminate\Support\Facades\Validator;use Illuminate\Support\Facades\Response;use Illuminate\Support\Facades\Config;use Illuminate\Support\Facades\File;use Intervention\Image\ImageManager;class ImageRepository{    public function upload( $form_data )    {        $validator = Validator::make($form_data, Image::$rules, Image::$messages);        if ($validator->fails()) {            return Response::json([                'error' => true,                'message' => $validator->messages()->first(),                'code' => 400            ], 400);        }        $photo = $form_data['file'];        $originalName = $photo->getClientOriginalName();        $originalNameWithoutExt = substr($originalName, 0, strlen($originalName) - 4);        $filename = $this->sanitize($originalNameWithoutExt);        $allowed_filename = $this->createUniqueFilename( $filename );        $filenameExt = $allowed_filename .'.jpg';        $uploadSuccess1 = $this->original( $photo, $filenameExt );        $uploadSuccess2 = $this->icon( $photo, $filenameExt );        if( !$uploadSuccess1 || !$uploadSuccess2 ) {            return Response::json([                'error' => true,                'message' => 'Server error while uploading',                'code' => 500            ], 500);        }        $sessionImage = new Image;        $sessionImage->filename      = $allowed_filename;        $sessionImage->original_name = $originalName;        $sessionImage->save();        return Response::json([            'error' => false,            'code'  => 200        ], 200);    }    public function createUniqueFilename( $filename )    {        $full_size_dir = Config::get('images.full_size');        $full_image_path = $full_size_dir . $filename . '.jpg';        if ( File::exists( $full_image_path ) )        {            // Generate token for image            $imageToken = substr(sha1(mt_rand()), 0, 5);            return $filename . '-' . $imageToken;        }        return $filename;    }    /**     * Optimize Original Image     */    public function original( $photo, $filename )    {        $manager = new ImageManager();        $image = $manager->make( $photo )->encode('jpg')->save(Config::get('images.full_size') . $filename );        return $image;    }    /**     * Create Icon From Original     */    public function icon( $photo, $filename )    {        $manager = new ImageManager();        $image = $manager->make( $photo )->encode('jpg')->resize(200, null, function($constraint){$constraint->aspectRatio();})->save( Config::get('images.icon_size')  . $filename );        return $image;    }    /**     * Delete Image From Session folder, based on original filename     */    public function delete( $originalFilename)    {        $full_size_dir = Config::get('images.full_size');        $icon_size_dir = Config::get('images.icon_size');        $sessionImage = Image::where('original_name', 'like', $originalFilename)->first();        if(empty($sessionImage))        {            return Response::json([                'error' => true,                'code'  => 400            ], 400);        }        $full_path1 = $full_size_dir . $sessionImage->filename . '.jpg';        $full_path2 = $icon_size_dir . $sessionImage->filename . '.jpg';        if ( File::exists( $full_path1 ) )        {            File::delete( $full_path1 );        }        if ( File::exists( $full_path2 ) )        {            File::delete( $full_path2 );        }        if( !empty($sessionImage))        {            $sessionImage->delete();        }        return Response::json([            'error' => false,            'code'  => 200        ], 200);    }    function sanitize($string, $force_lowercase = true, $anal = false)    {        $strip = array("~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "=", "+", "[", "{", "]",            "}", "\\", "|", ";", ":", "\"", "'", "‘", "’", "“", "”", "–", "—",            "&acirc;€”", "&acirc;€“", ",", "<", ".", ">", "/", "?");        $clean = trim(str_replace($strip, "", strip_tags($string)));        $clean = preg_replace('/\s+/', "-", $clean);        $clean = ($anal) ? preg_replace("/[^a-zA-Z0-9]/", "", $clean) : $clean ;        return ($force_lowercase) ?            (function_exists('mb_strtolower')) ?                mb_strtolower($clean, 'UTF-8') :                strtolower($clean) :            $clean;    }}

上传方法会验证 Image 模型中指定的字段规则,目前该规则只是限定上传图片的扩展。

在 upload 方法之后我们使用 reateUniqueFilename 方法为图片返回唯一文件名。

当唯一文件名返回后,我们将图片和对应文件名传递到 original 方法,该方法负责保存完整尺寸图片,对小尺寸图标图片我们使用 icon 方法进行处理。

这两个尺寸图片都保存好了之后,系统会在图片表 images 中创建一条新纪录。

你可能已经注意到了我将图片上传目录存放在了配置文件中,当然你可以自定义存放目录或者直接使用Laravel内置的方法。

<?phpreturn [    'full_size'   => env('UPLOAD_FULL_SIZE'),    'icon_size'   => env('UPLOAD_ICON_SIZE'),];

要让应用正常工作还需要将 .env.example 文件拷贝到 .env 文件,并且设置相应的配置值。注意到最后两个配置项的上传目录需要以 / 结尾,以我本地配置为例:

UPLOAD_FULL_SIZE=F:/xampp/htdocs/nonfu/dropzone-laravel-image-upload/public/images/full_size/UPLOAD_ICON_SIZE=F:/xampp/htdocs/nonfu/dropzone-laravel-image-upload/public/images/icon_size/

删除方法接收文件名并检查数据库中是否包含,然后在对应文件在是否存在于指定目录,如果两项都符合则该图片会被删除。

想要更加轻松地使用DropzoneJS实现图片上传,可以使用Laravel扩展包 Dropzoner 。

声明:本文为译文,原文: https://tuts.codingo.me/laravel-5-1-and-dropzone-js-auto-image-uploads-with-removal-links

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
PHP行動:現實世界中的示例和應用程序PHP行動:現實世界中的示例和應用程序Apr 14, 2025 am 12:19 AM

PHP在電子商務、內容管理系統和API開發中廣泛應用。 1)電子商務:用於購物車功能和支付處理。 2)內容管理系統:用於動態內容生成和用戶管理。 3)API開發:用於RESTfulAPI開發和API安全性。通過性能優化和最佳實踐,PHP應用的效率和可維護性得以提升。

PHP:輕鬆創建交互式Web內容PHP:輕鬆創建交互式Web內容Apr 14, 2025 am 12:15 AM

PHP可以輕鬆創建互動網頁內容。 1)通過嵌入HTML動態生成內容,根據用戶輸入或數據庫數據實時展示。 2)處理表單提交並生成動態輸出,確保使用htmlspecialchars防XSS。 3)結合MySQL創建用戶註冊系統,使用password_hash和預處理語句增強安全性。掌握這些技巧將提升Web開發效率。

PHP和Python:比較兩種流行的編程語言PHP和Python:比較兩種流行的編程語言Apr 14, 2025 am 12:13 AM

PHP和Python各有優勢,選擇依據項目需求。 1.PHP適合web開發,尤其快速開發和維護網站。 2.Python適用於數據科學、機器學習和人工智能,語法簡潔,適合初學者。

PHP的持久相關性:它還活著嗎?PHP的持久相關性:它還活著嗎?Apr 14, 2025 am 12:12 AM

PHP仍然具有活力,其在現代編程領域中依然佔據重要地位。 1)PHP的簡單易學和強大社區支持使其在Web開發中廣泛應用;2)其靈活性和穩定性使其在處理Web表單、數據庫操作和文件處理等方面表現出色;3)PHP不斷進化和優化,適用於初學者和經驗豐富的開發者。

PHP的當前狀態:查看網絡開發趨勢PHP的當前狀態:查看網絡開發趨勢Apr 13, 2025 am 12:20 AM

PHP在現代Web開發中仍然重要,尤其在內容管理和電子商務平台。 1)PHP擁有豐富的生態系統和強大框架支持,如Laravel和Symfony。 2)性能優化可通過OPcache和Nginx實現。 3)PHP8.0引入JIT編譯器,提升性能。 4)雲原生應用通過Docker和Kubernetes部署,提高靈活性和可擴展性。

PHP與其他語言:比較PHP與其他語言:比較Apr 13, 2025 am 12:19 AM

PHP適合web開發,特別是在快速開發和處理動態內容方面表現出色,但不擅長數據科學和企業級應用。與Python相比,PHP在web開發中更具優勢,但在數據科學領域不如Python;與Java相比,PHP在企業級應用中表現較差,但在web開發中更靈活;與JavaScript相比,PHP在後端開發中更簡潔,但在前端開發中不如JavaScript。

PHP與Python:核心功能PHP與Python:核心功能Apr 13, 2025 am 12:16 AM

PHP和Python各有優勢,適合不同場景。 1.PHP適用於web開發,提供內置web服務器和豐富函數庫。 2.Python適合數據科學和機器學習,語法簡潔且有強大標準庫。選擇時應根據項目需求決定。

PHP:網絡開發的關鍵語言PHP:網絡開發的關鍵語言Apr 13, 2025 am 12:08 AM

PHP是一種廣泛應用於服務器端的腳本語言,特別適合web開發。 1.PHP可以嵌入HTML,處理HTTP請求和響應,支持多種數據庫。 2.PHP用於生成動態網頁內容,處理表單數據,訪問數據庫等,具有強大的社區支持和開源資源。 3.PHP是解釋型語言,執行過程包括詞法分析、語法分析、編譯和執行。 4.PHP可以與MySQL結合用於用戶註冊系統等高級應用。 5.調試PHP時,可使用error_reporting()和var_dump()等函數。 6.優化PHP代碼可通過緩存機制、優化數據庫查詢和使用內置函數。 7

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
4 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能