欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ajax + Laravel 多文件上传

程序员文章站 2022-06-03 08:53:07
...

路由

C:\L\2017.11.15 MAMP\root\tagMoon\routes\web.php

Route::post('/multiUploadImg','aaa@qq.com');
Route::get('/upload', function(){
   return view('upload.main');
});

前端

C:\L\2017.11.15 MAMP\root\tagMoon\resources\views\upload\main.blade.php

截屏

before :

ajax + Laravel 多文件上传

(权简风格 :)

after :

ajax + Laravel 多文件上传

html

    <form id="form_uploadImg" method="post" enctype="multipart/form-data">
        <div class="file-field">
            <div class="btn btn-primary btn-sm">
                <span>Choose files</span>
                <input name="filesToUpload[]" id="input_multifileSelect" type="file" multiple>
            </div>
        </div>
    </form>
    <br><br><br>
    <div id="div_uploadedImgs"></div>

!!! 注意下面这一句,必须要有一对方括号:[]

<input name="filesToUpload[]"

js

        $(document).ready(function() {
            $('#input_multifileSelect').on('change', function(){
                var ajax_option= {
                    url: "multiUploadImg", 
                    // type : 'post', 默认是 form action
                    success: function ( data ) {
                        console.log( data );
                        showUploadedImgs( data.uploadedFiles );
                    }
                }
                $('#form_uploadImg').ajaxSubmit( ajax_option );
            });
        });
        // 显示上传的图片
        function showUploadedImgs( imgs ){
            $.each( imgs, function(index, img ) {
                var pic = '<p><img src="{0}"  alt="" /><br>{0} ( {1} - {2} )</p>';
                pic = pic.format( baseUrl + 'public/' + img.savedFile, img.name, img.size );
                $('#div_uploadedImgs').prepend( pic );
            });
        }
        // 为 String 类增加 format 函数
        String.prototype.format = function() {
            var str = this;
            for (var i = 0; i < arguments.length; i++) {
                var reg = new RegExp("\\{" + i + "\\}", "gm");
                str = str.replace(reg, arguments[i]);
            }
            return str;
        }

控制器(Controller)

C:\L\2017.11.15 MAMP\root\tagMoon\app\Http\Controllers\UploadCtrl.php


    /**
     * 接收上传文件
     * @param Request $request
     * @return array
     */
    public function multiUploadImg( Request $request ){

        // 重组数组,子函数
        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;
        }

        $imgFiles = $_FILES['filesToUpload']; // 与前端页面中的 input name=“filesToUpload[]” 相对应
        $uploadedFiles = array(); // 返回值

        if(!empty($imgFiles))
        {
            $img_desc = reArrayFiles( $imgFiles );
            $destinationPath = 'storage/uploads/'; //public 文件夹下面建 storage/uploads 文件夹

            foreach( $img_desc as $img )
            {
                $savedFile = $destinationPath.date('YmdHis',time()).mt_rand().'.'.pathinfo( $img['name'], PATHINFO_EXTENSION );
                move_uploaded_file($img['tmp_name'],  $savedFile);
                $img['savedFile'] = $savedFile ;
                array_push( $uploadedFiles, $img );
            }
        }

        $allowed_extensions = ["png", "jpg", "gif"];
        // TODO 判断文件类型

        return ['uploadedFiles' => $uploadedFiles ];
    }

response

ajax + Laravel 多文件上传

note

  • php : 7.1.5
  • Laravel : 5.4
  • jQuery : 3.3.1
  • Date : 2018.02.07

gif video

ajax + Laravel 多文件上传

download

http://download.csdn.net/download/lmn13/10244238

相关标签: ajax php laravel