laravel中上傳圖片並預覽
阿新 • • 發佈:2019-02-18
(1)需要工具uploadify
(2)需要uploadify文件一份(uploadify文件連結)
(3)demo模仿
<tr> <th>縮圖:</th> <td> <input type="text" size="50" name="art_thumb" > <input id="file_upload" name="file_upload" type="file" multiple="true"> <script src="{{asset('resources/org/uploadify/jquery.uploadify.min.js')}}" type="text/javascript"></script> <link rel="stylesheet" type="text/css" href="{{asset('resources/org/uploadify/uploadify.css')}}"> <script type="text/javascript"> <?php $timestamp = time();?> $(function() { $('#file_upload').uploadify({ 'buttonText':'圖片上傳', 'formData' : { 'timestamp' : '<?php echo $timestamp;?>', '_token' : '{{csrf_token()}}' //csrf驗證,不然會出現500 }, 'swf' : "{{asset('resources/org/uploadify/uploadify.swf')}}", 'uploader' : "{{url('admin/upload')}}", //處理upload的php方法,在router設定路由 , 'onUploadSuccess':function(file,data,response){ //上傳成功的操作:(1)顯示相對路徑(2)展示預覽圖 $('input[name=art_thumb]').val(data); $('#art_thumb_img').attr('src','/'+data); //需要在根目錄下面 } }); }); </script> <style> //優化樣式,變得更加優美 .uploadify{display:inline-block;} .uploadify-button{border:none; border-radius:5px; margin-top:8px;} table.add_tab tr td span.uploadify-button-text{color: #FFF; margin:0;} </style> </td> </tr>
<tr>
<th></th>
<td>
<img src="" alt="" id="art_thumb_img" style="max-width: 350px;max-height: 100px"> //展示縮圖
</td>
</tr>
$('#art_thumb_img').attr('src','/'+data); //需要在根目錄下面
返回給upload方法的資料如下
我們需要得到Filedata這個資料,可以用Input::file('Filedata')
(4)upload方法(demo)
客戶端<form action="" method="post" enctype="multipart/form-data"> <input type="file" name="myfile"> <input type="submit" name="submit" value="Submit"></form>提交到伺服器$file = Input::file('myflie');if($file -> isValid()){demo.php
//圖片上傳
public function upload(){
$file=Input::file('Filedata');
if($file->isValid()){
$entension=$file->getClientOriginalExtension();//獲得上傳檔案字尾
$newName = date('YmdHis').mt_rand(100,999).'.'.$entension;冰潔
$path = $file->move(base_path().'/uploads',$newName);//上傳檔案到伺服器指定目錄,並重命名【備註:base_path()指的是該程式根目錄】
$filepath='uploads/'.$newName; //給使用者一個相對路徑
return $filepath;
}
}
(5)設定預覽圖的大小
<img src="" alt="" id="art_thumb_img" style="max-width: 350px;max-height: 100px">