溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

php+ajax怎么實現(xiàn)無刷新上傳圖片

發(fā)布時間:2021-08-05 21:14:02 來源:億速云 閱讀:153 作者:chen 欄目:開發(fā)技術(shù)

本篇內(nèi)容主要講解“php+ajax怎么實現(xiàn)無刷新上傳圖片”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“php+ajax怎么實現(xiàn)無刷新上傳圖片”吧!

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>"); //函數(shù)處理

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', //數(shù)據(jù)格式為json 
      beforeSend: function() { //開始上傳 
        showimg.empty(); //清空顯示的圖片 
        imgsrc.val("");
        btn.html("上傳中..."); //上傳按鈕顯示上傳中 
      }, 
      uploadProgress: function(event, position, total, percentComplete) { 
      }, 
      success: function(data) { //成功 
        //獲得后臺返回的json數(shù)據(jù),顯示文件名,大小,以及刪除按鈕 
        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.后臺進(jìn)行處理

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.將返回的數(shù)據(jù)交給前端,進(jìn)行一些處理。

進(jìn)而提交到后臺數(shù)據(jù)庫。

php+ajax怎么實現(xiàn)無刷新上傳圖片

到此,相信大家對“php+ajax怎么實現(xiàn)無刷新上傳圖片”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI