Copy after login
When we click the upload image button, the image selection is triggered to implement Ajax upload. JavaScript code:
<script></script> <script> function upimg(obj) { if( obj.value == "" ) { return; } var formdata = new FormData(); //<input type="file" name="img" value="" /> formdata.append("img" , $(obj)[0].files[0]);//获取文件法二 $.ajax({ type : 'post', url : '/home/note/upimg', //接口 data : formdata, cache : false, processData : false, // 不处理发送的数据,因为data值是Formdata对象,不需要对数据做处理 contentType : false, // 不设置Content-type请求头 success : function(response){ console.log(response); var html = '<p style="position: relative;margin-right: 20px;margin-bottom: 15px;width: 132px;display: inline-block;border: 1px solid #CCC;background:#EEE;">' +'<span style="display: block;width: 120px;height: 80px;border: 1px solid #F2F1F0;margin: 5px;overflow: hidden;">' +'<img src="'+response+'" style="max-width:90%" / alt="Detailed explanation of how thinkPHP uses ajax to asynchronously upload images and display and delete them" >' +'' +'<input type="hidden" name="imgs[]" value="'+response+'" />' +'<a onclick="delImg(this);" style="z-index: 10;display: block;top: -8px;cursor:pointer;right: -8px;position:absolute;width: 20px;height: 20px;background: #CCC;border-radius:100%;text-align:center;line-height: 20px;border: 1px solid #C1C1C1;color: #555;">X' +''; $('#img-list-box').append(html); }, error : function(){ } }); } function delImg(obj) { $(obj).parent('p').remove(); } </script>
Copy after login
After clicking to select the image, it is handed over to the server for processing. php interface file:
public function upimg() { //验证 $file = request()->file('img'); // 移动到框架应用根目录/public/uploads/ 目录下 if($file){ $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads'); if($info){ // 成功上传后 获取上传信息 $img_src = '/uploads/'.$info->getSaveName(); echo $img_src; //返回ajax请求 }else{ // 上传失败获取错误信息 $this->error($file->getError()); } } }
Copy after login