redirect

jQuery-File-Upload

jQuery-File-Upload是一个jquery下的ajax文件上传插件,支持批量上传,github地址:https://github.com/blueimp/jQuery-File-Upload。

官方有个基本的使用教程,如果没有特别需求可以参考这个简单使用

https://github.com/blueimp/jQuery-File-Upload/wiki/Basic-plugin

官方的demo地址,感兴趣可以对照源码分析下,demo分别对应源码basic-plus.html,basic.html等文件
https://blueimp.github.io/jQuery-File-Upload/

批量上传图片

需要引入的css和js文件

<link rel="stylesheet" href="{{asset(\'js/jquery-fileupload/css/jquery.fileupload.css\')}}">
<link rel="stylesheet" href="{{asset(\'js/jquery-fileupload/css/jquery.fileupload-ui.css\')}}">

<script type="text/javascript" src="{{asset(\'js/jquery-fileupload/js/jquery.ui.widget.js\')}}"></script>
<script type="text/javascript" src="{{asset(\'js/jquery-fileupload/js/jquery.fileupload.js\')}}"></script>
<script type="text/javascript" src="{{asset(\'js/jquery-fileupload/js/jquery.iframe-transport.js\')}}"></script>

下载地址 https://github.com/blueimp/jQuery-File-Upload/releases ,下载后解压,将上面需要的文件放入项目相应目录。

html代码

<meta name="csrf-token" content="{{ csrf_token() }}">  
<form id="submit_form" action="{{route(\'work.store\')}}" method="post">
    {{csrf_field()}}
    <table class="add_tab">
        <tbody>
        <tr>
            <th>图片:<a id="start"></a></th>
            <td>
                <input id="fileupload" type="file" name="files[]" data-url="{{route(\'batch-upload\', [\'works\'])}}" multiple>
                <input id="file_path" type="hidden" name="file_path">
            </td>
        </tr>
        <tr>
            <th></th>
            <td>
                <div>
                    <div id="progress" style="width:50%;float:left">
                        <div class="bar" style="width: 0%;height:18px;background:green;"></div>
                    </div>
                    <div id="upload_finish" style="display:none;float:left;margin-left:15px;height:18px;line-height:18px;">上传完成</div>
                </div>
                <div style="clear:both"></div>
                <div id = "upload_list">
                </div>
            </td>
        </tr>
        <tr>
            <th></th>
            <td>
                <input type="submit" value="提交">
                <input type="button" class="back" onclick="history.go(-1)" value="返回">
            </td>
        </tr>
        </tbody>
    </table>
</form>

实现的js代码

        $(function () {
            $(\'#fileupload\').fileupload({
                dataType: \'json\',
                singleFileUploads: false,
                beforeSend: function(xhr) {
                    $(\'#upload_finish\').hide();
                    $(\'#progress .bar\').css(
                        \'width\',
                        \'0%\'
                    );
                    xhr.setRequestHeader("X-CSRF-TOKEN", $(\'meta[name="csrf-token"]\').attr(\'content\'));
                },
                progressall: function (e, data) {
                    var progress = parseInt(data.loaded / data.total * 100, 10);
                    $(\'#progress .bar\').css(
                        \'width\',
                        progress + \'%\'
                    );
                    if (progress == 100) {
                        $(\'#upload_finish\').show();
                    }
                },
                done: function (e, data) {
                    var files = data.result.data
                    for (i in files) {
                        $(\'#upload_list\').append(\'<img src="\' + files[i]+ \'" alt="" style="max-width: 350px; max-height:100px;margin:5px;">\');
                    }
                    $(\'#file_path\').val(files);
                }
            });
        });


laravel后台处理

Route::post(\'batch-upload/{dir_name}\', \'CommonController@batchUpload\')->name(\'batch-upload\');
    public function batchUpload(Request $request, $dir_name)
    {   
        try{
            $file_path = []; 
            if($request->hasFile(\'files\')){
                $files = $request->file(\'files\');
                foreach ($files as $file) {
                    $entension = $file->getClientOriginalExtension();
                    $new_name = date(\'YmdHis\').mt_rand(10000,99999).\'.\'.$entension;
                    $file_dir = public_path().\'/uploads/\'.$dir_name;
                    $file->move($file_dir,$new_name);
                    $file_path[] = \'/uploads/\'.$dir_name.\'/\'.$new_name;
                }   
            }   

            return $this->success($file_path);;
        }catch(\Exception $e){
            return $this->error(\'文件上传失败,请刷新后重试\');
        }   
    }

注意:

  • 1、ajax调用的时候需要考虑csrf问题,

html中加入头信息

<meta name="csrf-token" content="{{ csrf_token() }}">    
beforeSend: function(xhr) {
    xhr.setRequestHeader("X-CSRF-TOKEN", $(\'meta[name="csrf-token"]\').attr(\'content\'));
},
  • 2、一次上传多个文件,而不是循环调用

singleFileUploads: false,

上面配置是为了一次上传多个文件,否则的话是当你传入多个文件的时候会循环调用你的后台上传api。并且我在跑官方文档的时候发现,一次上传n个图片,会触发n次add回调,并且每次回掉获取data.files对象都是所有的n个文件,想要单独处理每个文件很麻烦,所以我直接每次自动上传,并且都是上传所有选中的文件。

上传完成后效果

分类:

技术点:

相关文章: