标签:false ash 获取 button put display func image trigger
本文展示了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
标签:false ash 获取 button put display func image trigger
原文地址:https://www.cnblogs.com/mclaoliu/p/13185338.html