PHP+ajax實(shí)現(xiàn)上傳、刪除、修改單張圖片及后臺(tái)處理邏輯操作詳解
本文實(shí)例講述了PHP+ajax實(shí)現(xiàn)上傳、刪除、修改單張圖片及后臺(tái)處理邏輯操作。分享給大家供大家參考,具體如下:
2019-07-04更新
更新修改原因:
- 前臺(tái)界面ui顯示不好看
- 后臺(tái)處理邏輯混亂,涉及到多張圖片處理起來很麻煩,所以修改成通過ajax上傳/刪除圖片。
效果:
上傳前:
上傳后:
撤銷后:
以下是更新的代碼:
HTML
- 代碼:
<div class="form-group"> <label for="username" class="col-sm-2 control-label no-padding-right">縮略圖 </label> <div class="col-sm-6"> <input type="hidden" id="pic" value="" name="pic"> <!-- 要將父布局的position設(shè)置為relative,父布局將無法包裹input --> <a href="javascript:void(0);" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="btn btn-palegreen" style="position: relative;margin-right: 10px;" id="xian"> <!--設(shè)置input的position為absolute,使其不按文檔流排版,并設(shè)置其包裹整個(gè)布局 --> <!-- 設(shè)置opactity為0,使input變透明 --> <input type="file" name="pic" accept="image/*" style="opacity: 0;position: absolute">上傳圖片</a> <a href="javascript:void(0);" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="btn btn-magenta" onclick="delimg(this)" style="display: none" id="che">撤銷圖片</a> </div> </div>
要點(diǎn): 重點(diǎn)都在注釋里了。
參考: JS+HTML實(shí)現(xiàn)自定義上傳圖片按鈕并顯示圖片
JS
- 代碼:
//上傳圖片 //對(duì)input[type=file]監(jiān)聽 $("input[name=pic]").on('change',function () { var e=$(this); var file=e[0].files[0]; var formData=new FormData(); formData.append("pic",file);//這里給圖片賦的name要與下面php中接收的post值對(duì)應(yīng) $.ajax({ url: "{:url('upimg')}", type:'POST', cache: false, //上傳文件不需要緩存 data:formData, processData: false, // 告訴jQuery不要去處理發(fā)送的數(shù)據(jù)(規(guī)定通過請(qǐng)求發(fā)送的數(shù)據(jù)是否轉(zhuǎn)換為查詢字符串。默認(rèn)是 true。) contentType: false, // 告訴jQuery不要去設(shè)置Content-Type請(qǐng)求頭(發(fā)送數(shù)據(jù)到服務(wù)器時(shí)所使用的內(nèi)容類型。默認(rèn)是:"application/x-www-form-urlencoded"。) success:function (data) { if (data){ $("#xian").hide(); $("#che").show(); $("#pic").val(data); e.parents(".col-sm-6").append("[外鏈圖片轉(zhuǎn)存失敗(img-wg119lWd-1562224226091)(https://mp.csdn.net/mdeditor/%22+data+%22)]"); layer.msg('上傳成功', {icon: 6}) } else{ layer.msg('上傳失敗', {icon: 5}) } } }) }) //刪除圖片 function delimg(e) { layer.confirm('確定刪除?', {icon: 3, title:'提示'}, function(index){ //do something var id="{$article.id}"; var imgpath = $(e).siblings('img:last').attr('src'); $.ajax({ url:"{:url('delimg')}", type:'post', data: {pic:imgpath}, success:function (data) { if(data){ $("#xian").show(); $("#che").hide(); $("#pic").val(""); $(e).siblings('img').hide(); layer.msg('刪除成功', {icon: 6}) }else{ layer.msg('刪除失敗', {icon: 5}) } } }) layer.close(index); }); }
這里有句代碼展示有問題,源碼如下:
要點(diǎn) :
JS formDate的使用
上傳成功后返回圖片路徑,塞到input[type=hidden]框里,之后會(huì)隨著表單提交上去,保存在數(shù)據(jù)庫(kù)中。
參考: JavaScript實(shí)現(xiàn)圖片上傳并預(yù)覽并提交ajax
PHP
- 代碼:
//ajax上傳圖片 public function upimg() { $file = request()->file('pic');//這里接收到的圖片name要與上面js中formData賦值對(duì)應(yīng) if ($file) { $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'articleimg'); $imgpath = '/uploads/articleimg/' . $info->getSaveName(); return $imgpath; }else{ return 0; } } //ajax刪除圖片 public function delimg() { $data = input('post.'); if ($pic = $data['pic']) { $imppath = ROOT_PATH . 'public' . $pic; if (@unlink($imppath)) { //這里要對(duì)數(shù)據(jù)庫(kù)中的Pic字段進(jìn)行即時(shí)修改。嗯嗯 $re=db('article')->where('id', $data['id'])->setField('pic', ''); if ($re!==false){ return 1; } } else { return 0; } } else { return '參數(shù)錯(cuò)誤'; } }
分割線(下面是前幾天寫的答案,邏輯混亂。。。就不要看了吧)
- 前臺(tái)處理:
- 添加一個(gè)
<input type="hidden" value="" name="pic">
,會(huì)隨著post一起提交到后臺(tái)中去。
- 后臺(tái)處理分為兩步
- 收到的post數(shù)據(jù)data中pic字段值為空時(shí),且該欄目之前有圖片,則執(zhí)行刪除原來圖片操作;
- 如果上傳了新圖片,則移動(dòng)到指定目錄下,并查詢?cè)摍谀恐笆欠裼袌D片,如果有,則執(zhí)行刪除原來圖片操作;
html代碼
<div class="form-group"> <label for="username" class="col-sm-2 control-label no-padding-right">欄目圖片</label> <div class="col-sm-6"> <input type="hidden" name="pic" value="{$ca.pic}" id="pic"> <input type="file" id="file" accept="image/*" name="pic" style="display: inline-block"> <a href="javascript:void(0);" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="btn btn-warning shiny" id="returnimg"><i class="menu-icon fa fa-repeat"></i>撤銷圖片</a> {notempty name='$ca.pic'} <img src="{$ca.pic}" alt="圖片" id="img" style="width: 50px;margin-top:10px;display: block"> {else/} <img src="" alt="圖片" id="img" style="width: 50px;margin-top:10px;display: none"> {/notempty} </div> </div>
js代碼
<script> //圖片撤銷 $("#returnimg").on('click', function () { let img = $("#img").attr('src'); if (img) { layer.confirm('確定撤銷圖片?', {icon: 3, title: '提示'}, function (index) { $("#pic").val(""); $("#img").attr('src', '').css('display', 'none'); layer.close(index); }); } else { layer.msg('未選擇圖片', {icon: 0}); } }) </script>
php代碼
//1.如果欄目原來有圖片&&現(xiàn)在撤銷了,就刪除舊圖片 if (($cate['pic'] != false) && ($data['pic'] == false)) { @unlink(ROOT_PATH . 'public' . $cate['pic']); } //如果上傳了新的圖片 $file = request()->file('pic'); // 移動(dòng)到框架應(yīng)用根目錄/public/uploads/ 目錄下 if ($file) { $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'cateimg'); if ($info) { // 成功上傳后 獲取上傳信息 $pic = '/uploads/cateimg/' . $info->getSaveName(); $data['pic'] = $pic; //2.新的圖片上傳成功后,如果欄目原來有圖片,刪除原來欄目圖片 if ($cate['pic']) { @unlink(ROOT_PATH . 'public' . $cate['pic']); } } else { // 上傳失敗獲取錯(cuò)誤信息 $this->error($file->getError()); } }
更多關(guān)于PHP相關(guān)內(nèi)容可查看本站專題:《PHP+ajax技巧與應(yīng)用小結(jié)》、《PHP網(wǎng)絡(luò)編程技巧總結(jié)》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫(kù)操作入門教程》及《php常見數(shù)據(jù)庫(kù)操作技巧匯總》
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。
相關(guān)文章
php中調(diào)用其他系統(tǒng)http接口的方法說明
本篇文章主要是對(duì)php中調(diào)用其他系統(tǒng)http接口的方法進(jìn)行了介紹,需要的朋友可以過來參考下,希望對(duì)大家有所幫助2014-02-02PHP strtotime函數(shù)用法、實(shí)現(xiàn)原理和源碼分析
這篇文章主要介紹了PHP strtotime函數(shù)用法、實(shí)現(xiàn)原理和源碼分析,本文講解了strtotime函數(shù)的一些用法、strtotime函數(shù)的實(shí)現(xiàn)基本原理、strtotime(“-1 month”)求值失敗的原因等內(nèi)容,需要的朋友可以參考下2015-02-02Joomla下利用configuration.php存儲(chǔ)簡(jiǎn)單數(shù)據(jù)
Joomla下利用configuration.php存儲(chǔ)簡(jiǎn)單數(shù)據(jù)的代碼,需要的朋友可以參考下。2010-05-05PHP實(shí)現(xiàn)的策略模式簡(jiǎn)單示例
這篇文章主要介紹了PHP實(shí)現(xiàn)的策略模式,結(jié)合簡(jiǎn)單實(shí)例形式分析了策略模式的原理與實(shí)現(xiàn)方法,需要的朋友可以參考下2017-08-08PHP連接數(shù)據(jù)庫(kù)實(shí)現(xiàn)頁(yè)面增刪改查效果
這篇文章主要介紹了如何利用PHP實(shí)現(xiàn)連接SQL數(shù)據(jù)庫(kù),從而對(duì)頁(yè)面進(jìn)行增刪改查功能,文中的示例代碼講解詳細(xì),感興趣的可以了解一下2022-03-03php實(shí)現(xiàn)的發(fā)送帶附件郵件類實(shí)例
這篇文章主要介紹了php實(shí)現(xiàn)的發(fā)送帶附件郵件類,是php程序設(shè)計(jì)中非常常見的實(shí)用技巧,實(shí)例演示了郵件類及對(duì)應(yīng)的demo示例,需要的朋友可以參考下2014-09-09php使用pclzip類實(shí)現(xiàn)文件壓縮的方法(附pclzip類下載地址)
這篇文章主要介紹了php使用pclzip類實(shí)現(xiàn)文件壓縮的方法,分析了使用pclzip類的具體步驟與實(shí)現(xiàn)文件壓縮的相關(guān)技巧,并附帶pclzip類文件的下載地址,需要的朋友可以參考下2016-04-04