本文分享了php结合ajax实现无刷新上传图片的实例代码,分享给大家,希望大家可以和小编一起学习学习,共同进步。
1.引入文件
1 2 3 4 5 | <!--图片上传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部分
1 2 3 4 5 6 7 8 9 10 11 12 | <div class = "upimg" >
<input name= "icon" type= "text" class = "imgsrc" value= "<!--{$contents.icon}-->" />
<div class = "showimg" >
<!--{ if $contents .icon}-->
<img src= "/static/imghw/default1.png" data-src= "<!--{$contents.icon}-- alt=" php+ajax无刷新上传图片实例代码_PHP " >" class = "lazy" height= "120px" >
<!--{/ if }-->
</div>
<div class = "btn" style= "height:20px;" >
<span>添加图片</span>
<input class = "fileupload" type= "file" name= "pic[]" >
</div>
</div>
|
ログイン後にコピー
3.给fileupload加上表单
1 2 | $( ".fileupload" ).wrap( "<form action='/bookstore/book/uploadpic' method='post' enctype='multipart/form-data'></form>" );
|
ログイン後にコピー
4.ajax文件上传
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | 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({
beforeSend: function () {
showimg. empty ();
imgsrc.val( "" );
btn.html( "上传中..." );
},
uploadProgress: function (event, position, total, percentComplete) {
},
success: function (data) {
var img = data;
imgsrc.val( "" );
imgsrc.val(img);
showimg.html( "<img src=" / static /imghw/default1.png " data-src=" http:
btn.html( "上传成功" );
},
error: function (xhr){
btn.html( "上传失败" );
}
});
});
});
|
ログイン後にコピー
5.后台进行处理
1 2 3 4 5 6 | 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程序设计有所帮助。