本文展示了ThinkPHP6 上傳圖片代碼demo, 代碼親測可用.
HTML部分代碼
1 <tr> 2 <th class="font-size-sm" style="width:15%;height:100px;">商品圖片</th> 3 <td> 4 <div class="custom-file"> 5 <div id="uploadImage" style="width:100px;height:100px;display: inline;"></div> 6 <button id="uploadBtn" class="btn btn-outline-info font-size-sm">選擇圖片</button> 7 <input type="file" name="imgFile" id="imgFile" style="display: none;"> 8 </div> 9 </td> 10 </tr>
JS部分代碼
1 $(document).ready(function(){ 2 var input = $("#imgFile"); 3 // 將上傳按鈕綁定到input['file']上 4 $("#uploadBtn").click(function(){ 5 input.trigger("click"); 6 }); 7 input.change(function () { 8 // 如果value不為空,調用文件加載方法 9 if ($(this).val() !== "") { 10 doUpload(this); 11 } 12 }); 13 }); 14 15 // 上傳圖片 16 var SCOPE = { 17 'uploadUrl': '{:url("' + urlPath +'/upload")}', 18 }; 19 function doUpload() { 20 var formData = new FormData($( "#myform" )[0]), 21 appendDiv = $("#uploadImage"), 22 imageUrl = '', 23 imageDiv = ''; 24 $.ajax({ 25 url: SCOPE.uploadUrl , 26 type: 'POST', 27 data: formData, 28 async: false, 29 cache: false, 30 contentType: false, 31 processData: false, 32 success: function (result) { 33 if(result.status === 1){ 34 appendDiv.empty(); 35 imageUrl = '/storage/' + result.data; 36 imageDiv = ''; 37 appendDiv.append(imageDiv); 38 } 39 }, 40 }); 41 }
ThinkPHP中的上傳方法
1 /** 2 * 圖片上傳(ajax) 3 * @return \think\Response|void 4 * @throws \Exception 5 */ 6 public function upload() 7 { 8 // 獲取表單上傳文件 例如上傳了001.jpg 9 $file = request()->file('imgFile'); 10 try{ 11 // 驗證 12 validate(['imgFile'=>[ 13 'fileSize' => 410241024, 14 'fileExt' => 'jpg,jpeg,png,bmp,gif', 15 'fileMime' => 'image/jpeg,image/png,image/gif', //這個一定要加上,很重要我認為! 16 ]])->check(['imgFile' => $file]); 17 18 // 上傳圖片到本地服務器 19 $saveName = \think\facade\Filesystem::disk('public')->putFile( 'merchant', $file, 'data'); 20 $this->result(1, '圖片上傳成功!', $saveName, 'json'); 21 } catch (\Exception $e) { 22 // 驗證失敗 輸出錯誤信息 23 return $this->exceptionHandle($e, 24 '圖片上傳失敗!' . $e->getMessage(), 25 'json', 26 ''); 27 } 28 }
本文轉載自老劉博客, 轉載請注明出處,謝謝!
http://laoliu.pro/php/15.html
————————————————
版權聲明:本文為CSDN博主「老劉pro」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/a33130317/article/details/106933622