thinkphpÔõôÉÏ´«Í¼Æ¬
µÚÒ»²½£ºÉèÖÃÐëÒª²ÎÊý
ÔÚconfig.phpÉèÖÃÎļþÖУ¬ÐèÒªÏÈÉèÖÃÉÏ´«Îļþ·¾¶¡¢ÏÞÖÆͼƬ¾ÞϸºÍÎļþÀàÐ͵ȲÎÊý¡£ÏêϸÉèÖÃÈçÏ£º
return [ 'upload_path' => './uploads/', //ÉÏ´«Îļþ·¾¶ 'img_max_size' => 2 * 1024 * 1024, //×î´óÉÏ´«Í¼Æ¬¾Þϸ 'img_allow_types' => 'jpg,png,gif,jpeg', //ÔÊÐíÉÏ´«µÄÎļþÀàÐÍ ];
µÇ¼ºó¸´ÖÆ
µÚ¶þ²½£º±àдͼƬÉÏ´«´úÂë
ÔÚThinkPHPÖУ¬ÎÒÃÇ¿ÉÒÔͨ¹ýʹÓÃÉÏ´«ÀàÀ´ÊµÏÖͼƬµÄÉÏ´«¹¦Ð§¡£ÏȽ«ÉÏ´«ÀർÈ룺
Á¬Ã¦Ñ§Ï°¡°PHPÃâ·ÑѧϰÌõ¼Ç£¨ÉîÈ룩¡±£»
use think\facade\Request; use think\facade\Filesystem; class ImageUpload { public function upload() { $img_file = Request::file('img'); //»ñÈ¡ÉÏ´«µÄͼƬÎļþ $img_path = config('upload_path'); //»ñÈ¡ÉÏ´«Â·¾¶ $max_size = config('img_max_size'); //»ñÈ¡×î´óÎļþ³ß´ç $allow_types = config('img_allow_types'); //»ñÈ¡ÔÊÐíÉÏ´«µÄÀàÐÍ //ÅжÏÉÏ´«ÎļþÊÇ·ñÓÐÓᢾÞϸÊÇ·ñÇкϡ¢ÀàÐÍÊÇ·ñ׼ȷ if (!$img_file->isValid()) { return ['code' => 1, 'msg' => 'ÉÏ´«Í¼Æ¬ÎÞЧ']; } if ($img_file->getSize() > $max_size) { return ['code' => 2, 'msg' => 'ÉÏ´«Í¼Æ¬¾ÞϸÁè¼ÝÏÞÖÆ']; } if (!in_array($img_file->extension(), explode(',', $allow_types))) { return ['code' => 3, 'msg' => 'ÉÏ´«Í¼Æ¬ÀàÐͲ»Ö§³Ö']; } //ÉÏ´«Îļþ $file_info = $img_file->move($img_path); if ($file_info === false) { return ['code' => 4, 'msg' => 'ÉÏ´«Í¼Æ¬Ê§°Ü£¬ÇëÖØÊÔ']; } //·µ»ØÉÏ´«ÀÖ³ÉÐÅÏ¢ $file_name = $file_info->getSaveName(); $file_url = Filesystem::getDiskConfig('public', ['url' => '/'])->getVisibility()->url($img_path . $file_name); return ['code' => 0, 'msg' => 'ÉÏ´«Í¼Æ¬ÀÖ³É', 'url' => $file_url]; } }
µÇ¼ºó¸´ÖÆ
µÚÈý²½£ºÅ²ÓÃͼƬÉÏ´«´úÂë
½ÓÏÂÀ´£¬ÎÒÃÇ¿ÉÒÔÔÚ¿ØÖÆÆ÷ÖÐŲÓÃͼƬÉÏ´«´úÂ룬²¢»ñÈ¡ÉÏ´«Ð§¹û£º
public function uploadImage() { $result = (new ImageUpload())->upload(); echo json_encode($result); }
µÇ¼ºó¸´ÖÆ
×îºó£¬ÎÒÃÇÖ»ÐèÔÚÇ°¶ËÒ³ÃæÖÐʹÓÃajax½«Í¼Æ¬ÎļþÉÏ´«ÖÁЧÀͶ˼´¿É£º
<form id="image-form" action="/uploadImage" method="post" enctype="multipart/form-data"> <input type="file" id="img-file" name="img" accept="image/*"> <button type="submit">ÉÏ´«</button> </form> <script> $(document).on('submit', '#image-form', function (event) { event.preventDefault(); var formData = new FormData(document.getElementById('image-form')); $.ajax({ url: '/uploadImage', type: 'post', data: formData, contentType: false, processData: false, dataType: 'json', success: function (res) { //´¦ÀíÉÏ´«Ð§¹û }, error: function (xhr, textStatus, errorThrown) { console.log(errorThrown); } }); }); </script>
µÇ¼ºó¸´ÖÆ
ÒÔÉϾÍÊÇthinkphpÔõôÉÏ´«Í¼Æ¬µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡
ÃâÔð˵Ã÷£ºÒÔÉÏչʾÄÚÈÝȪԴÓÚÏàÖúýÌå¡¢ÆóÒµ»ú¹¹¡¢ÍøÓÑÌṩ»òÍøÂçÍøÂçÕûÀí£¬°æȨÕùÒéÓë±¾Õ¾Î޹أ¬ÎÄÕÂÉæ¼°¿´·¨Óë¿´·¨²»´ú±í尊龙凯时人生就是搏ÂËÓÍ»úÍø¹Ù·½Ì¬¶È£¬Çë¶ÁÕß½ö×ö²Î¿¼¡£±¾ÎĽӴýתÔØ£¬×ªÔØÇë˵Ã÷À´ÓÉ¡£ÈôÄúÒÔΪ±¾ÎÄÇÖÕ¼ÁËÄúµÄ°æȨÐÅÏ¢£¬»òÄú·¢Ã÷¸ÃÄÚÈÝÓÐÈκÎÉæ¼°ÓÐÎ¥¹«µÂ¡¢Ã°·¸Ö´·¨µÈÎ¥·¨ÐÅÏ¢£¬ÇëÄúÁ¬Ã¦ÁªÏµ尊龙凯时人生就是搏ʵʱÐÞÕý»òɾ³ý¡£