本文實例講述了Thinkphp框架+Layui實現圖片/文件上傳功能。分享給大家供大家參考,具體如下:
在項目中用到了,再網上找了現成的代碼都是借口異常或者非法上傳,所以在一番摸索搞定之后拿來和大家分享。
html:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
< form class = "layui-form layui-form-pane" action = "" style = "margin-top:20px;" enctype = "multipart/form-data" > < center > < div class = "layui-upload-drag" id = "uploadBanner" > < img class = "layui-upload-img" id = "upload-photo" > < i class = "layui-icon" id = "upload-icon" ></ i > < p >點擊上傳,或將文件拖拽到此處</ p > < p >建議尺寸1920*512</ p > </ div > < input type = "hidden" id = "res" name = "banner_photo" value = "" lay-verify = "required" /> < div class = "layui-form-item" style = "margin-top:10px;" > < button class = "layui-btn" lay-submit = "" lay-filter = "sub" >提交</ button > </ div > < div id = "demoText" ></ div > </ center > </ form > |
JS:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
layui.use( 'upload' , function (){ var $ = layui.jquery ,upload = layui.upload; //普通圖片上傳 var uploadInst = upload.render({ elem: '#uploadBanner' ,url: "{:U('Api/doUploadPic')}" ,before: function (obj){ //預讀本地文件示例,不支持ie8 obj.preview( function (index, file, result){ $( '#upload-photo' ).attr( 'src' , result); //圖片鏈接(base64) $( '#upload-photo' ).attr( 'style' , 'height:10rem;' ); $( '#upload-icon' ).attr( 'style' , 'display:none;' ); }); } ,done: function (res, index, upload){ //如果上傳失敗 if (res.code > 0){ return layer.msg( '上傳失敗' ); } //上傳成功 console.log( "成功啦!" + obj2string(res) + " " + index + " " + upload); } ,error: function (){ //演示失敗狀態,并實現重傳 var demoText = $( '#demoText' ); demoText.html( '<span style="color: #FF5722;">上傳失敗</span> <a class="layui-btn layui-btn-xs demo-reload">重試</a>' ); demoText.find( '.demo-reload' ).on( 'click' , function (){ uploadInst.upload(); }); } }); }); |
PHP接口:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public function doUploadPic() //上傳模塊 { $upload = new \Think\Upload(); $upload ->maxSize = 3145728; $upload ->exts = array ( 'jpg' , 'gif' , 'png' , 'jpeg' ); $upload ->rootPath = './Public/' ; // 設置附件上傳根目錄 $upload ->savePath = 'upload/' ; // 設置附件上傳子目錄 $info = $upload ->upload(); if (! $info ){ $this ->error( $upload ->getError()); } else { foreach ( $info as $file ){ $data = '/Public' . $file [ 'savepath' ] . $file [ 'savename' ]; $file_a = $data ; echo '{"code":0,"msg":"成功上傳","data":{"src":"' . $file_a . '"}}' ; } } } |
圖片就上傳到/Public/upload文件夾下了:
希望本文所述對大家基于ThinkPHP框架的PHP程序設計有所幫助。
原文鏈接:https://blog.csdn.net/qq_17497931/article/details/81290604