很多项目中需要用到即时上传功能,比如,选择本地图片后,立即上传并显示图像。本文结合实例讲解如何使用jQuery和PHP实现Ajax即时上传文件的功能,用户只需选择本地图片确定后即实现上传,并显示上传进度条,上传完成后,显示图片信息。
可以看出,我们用于上传文件的html中并没有出现form表单,而正常的上传功能是要依赖form表单的。我们的form表单是动态插入的,这样可以避免一个大表单中出现多个form。
首先定义各种变量,注意动态将表单元素form插入到上传按钮部位,并且form的属性enctype必须设置为:multipart/form- data。然后当点击“上传附件”按钮,选择要上传的文件后,调用jquery.form插件的ajaxSubmit方法,如下代码说明。
$(function () {
var bar = $('.bar');
var percent = $('.percent');
var showimg = $('#showimg');
var progress = $(".progress");
var files = $(".files");
var btn = $(".btn span");
$("#fileupload").wrap("
");
$("#fileupload").change(function(){ //选择文件
$("#myupload").ajaxSubmit({
dataType: 'json', //数据格式为json
beforeSend: function() { //开始上传
showimg.empty(); //清空显示的图片
progress.show(); //显示进度条
var percentVal = '0%'; //开始进度为0%
bar.width(percentVal); //进度条的宽度
percent.html(percentVal); //显示进度为0%
btn.html("上传中..."); //上传按钮显示上传中
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%'; //获得进度
bar.width(percentVal); //上传进度条宽度变宽
percent.html(percentVal); //显示上传进度百分比
},
success: function(data) { //成功
//获得后台返回的json数据,显示文件名,大小,以及删除按钮
files.html("
"+data.name+"("+data.size+"k) 删除");
//显示上传后的图片
var img = "http://demo.helloweba.com/upload/files/"+data.pic;
showimg.html("

");
btn.html("添加附件"); //上传按钮还原
},
error:function(xhr){ //上传失败
btn.html("上传失败");
bar.width('0');
files.html(xhr.responseText); //返回失败信息
}
});
});
...
});
关于jquery.form插件的更多信息,请参阅form插件官网:http://malsup.com/jquery/form/,官网中详细介绍了form插件的API和各种选项设置以及示例。
action.php中需要处理图片上传以及删除图片。图片上传时需要验证格式和大小,然后通过move_uploaded_file()方法上传图片,最后返回json格式的数据。删除图片时使用unlink()即可完成删除操作。