说明
前端使用了 jQuery.form.js 实现 Ajax 表单提交,后端使用的是著名的 Laravel(5.4)进行接收、存储,支持一次选择多个文件,选择确定后立即上传,并显示上传后的链接。
gif video
路由
C:\L\2017.11.15 MAMP\root\tagMoon\routes\web.PHP
Route::post('/multiUploadImg','UploadCtrl@multiUploadImg'); Route::get('/upload',function(){ return view('upload.main'); });
前端
C:\L\2017.11.15 MAMP\root\tagMoon\resources\views\upload\main.blade.PHP
截屏
before :
(权简风格 :)
after :
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
note
- PHP : 7.1.5
- Laravel : 5.4
- jQuery : 3.3.1
- Date : 2018.02.07