本篇內容主要講解“php+ajax怎么實現無刷新上傳圖片”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“php+ajax怎么實現無刷新上傳圖片”吧!
1.引入文件
<!--圖片上傳begin--> <script type="text/javascript" src="/js/jquery.form.js"></script> <script type="text/javascript" src="/js/uploadImg.js"></script> <link href="/css/uploadImg.css" rel="stylesheet" type="text/css" /> <!--圖片上傳end-->
2.html部分
<div class="upimg">
<input name="icon" type="text" class="imgsrc" value="<!--{$contents.icon}-->" />
<div class="showimg">
<!--{if $contents.icon}-->
<img src="<!--{$contents.icon}-->" height="120px">
<!--{/if}-->
</div>
<div class="btn" >
<span>添加圖片</span>
<input class="fileupload" type="file" name="pic[]">
</div>
</div>3.給fileupload加上表單
/*圖片上傳*/
$(".fileupload").wrap("<form action='/bookstore/book/uploadpic' method='post' enctype='multipart/form-data'></form>"); //函數處理4.ajax文件上傳
jQuery(function ($) {
$(".fileupload").change(function(){ //選擇文件
if ('' === $(this).val()) return;
var upimg = $(this).parent().parent().parent();
var showimg = upimg.find('.showimg');
var btn = upimg.find('.btn span');
var imgsrc = upimg.find('.imgsrc');
$(this).parent().ajaxSubmit({
//dataType: 'json', //數據格式為json
beforeSend: function() { //開始上傳
showimg.empty(); //清空顯示的圖片
imgsrc.val("");
btn.html("上傳中..."); //上傳按鈕顯示上傳中
},
uploadProgress: function(event, position, total, percentComplete) {
},
success: function(data) { //成功
//獲得后臺返回的json數據,顯示文件名,大小,以及刪除按鈕
var img = data;
//顯示上傳后的圖片
imgsrc.val("");
imgsrc.val(img);
showimg.html("<img width='120' height='120' src='"+img+"'>");
btn.html("上傳成功"); //上傳按鈕還原
},
error:function(xhr){ //上傳失敗
btn.html("上傳失敗");
}
});
});
});5.后臺進行處理
public function uploadpicAction(){ //圖片上傳和顯示
$data = "";
$src = $this->uploadFiles2($imgpath = "/upload/book" ,$filesname = "pic");
isset($src[0]['src']) && $src[0]['src'] ? $data = $this->concaturl($src[0]['src']) : null;
echo $data;
}6.將返回的數據交給前端,進行一些處理。
進而提交到后臺數據庫。

到此,相信大家對“php+ajax怎么實現無刷新上傳圖片”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。