jQuery AjaxUpload 上传图片代码 - Web前端
作者:98wpeu发布时间:2026-08-18分类:网页前端技术浏览:1
本次使用AjaxUPload做为上传客户端无刷上传插件,其最新版本为3.9,官方地址:http://valums.com/ajax-upload/
在页面中引入 JQuery.min.1.4.2.JS 和 ajaxupload.js
<script src="Scripts/jQuery-1.4.2.min.js" type="text/javascript"></script> <script src="Scripts/ajaxupload3.9.js" type="text/JavaScript"></script>
html 代码:
<style type="text/CSS">
#txtFileName {
width: 300px;
}
.BTnsubmit{border-bottom: #cc4f00 1px solid; border-left: #ff9000 1px solid;border-top: #ff9000 1px solid; border-right: #cc4f00 1px solid;text-align: center; padding: 2px 10px; line-height: 16px; background: #e36b0f; height: 24px; color: #fff; font-size: 12px; cursor: pointer;}
</style>
上传图片:<input type="text" id="txtFileName" /><div id="btnUp" style="width:300px;" class=btnsubmit >浏览</div>
<div id="imglist"></div>
js代 码:
<script type="text/Javascript">
$(function () {
var button = $('#btnUp'), interval;
new AjaxUpload(button, {
//action: 'upload-test.PHP',文件上传服务器端执行的地址
action: '/handler/AjaxuploadHandler.ashx',
name: 'myfile',
onSubmit: function (file, ext) {
if (!(ext && /^(jpg|jpeg|JPG|JPEG)$/.test(ext))) {
alert('图片格式不正确,请选择 jpg 格式的文件!', '系统提示');
return false;
}
// change button text, when User selects file
button.text('上传中');
// If you want to allow uploading only 1 file at time,
// you can disable upload button
this.disable();
// Uploding -> Uploading. -> Uploading...
interval = window.SetInterval(function () {
var text = button.text();
if (text.length < 10) {
button.text(text + '|');
} else {
button.text('上传中');
}
}, 200);
},
onComplete: function (file, response) {
//file 本地文件名称,response 服务器端传回的信息
button.text('上传图片(只允许上传JPG格式的图片,大小不得大于150K)');
window.clearInterval(interval);
// enable upload button
this.enable();
var k = response.Replace("<PRE>", "").replace("</PRE>", "");
if (k == '-1') {
alert('您上传的文件太大啦!请不要超过150K');
}
else {
alert("服务器端传回的串:"+k);
alert("本地文件名称:"+file);
$("#txtFileName").val(k);
$("<img />").appendTo($('#imglist')).attr("src", k);
}
}
});
});
</script>
服务器端 ajaxuploadhandler.ashx 代码
public void ProcessRequest(httpContext context)
{
context.Response.ContentType = "text/plAIn";
HTTPpostedFile postedFile = context.Request.Files[0];
string savePath = "/upload/images/";
int filelength = postedFile.ContentLength;
int fileSize = 163600; //150K
String fileName = "-1"; //返回的上传后的文件名
if (filelength <= fileSize)
{
byte[] buffer = new byte[filelength];
postedFile.InputStream.Read(buffer, 0, filelength);
fileName = UploadImage(buffer, savePath, "jpg");
}
context.Response.Write(fileName);
}
public static string UploadImage(byte[] imgBuffer, string uploadpath, string ext)
{
try
{
System.IO.MemoryStream m = new MemoryStream(imgBuffer);
if (!Directory.Exists(HttPContext.Current.Server.MAPPath(uploadpath)))
Directory.CreateDirectory(Httpcontext.Current.Server.Mappath(uploadpath));
string imgname = CreateIDcode() + "." + ext;
string _path = HttpContext.Current.Server.mapPath(uploadpath) + imgname;
Image img = Image.FromStream(m);
if (ext == "jpg")
img.Save(_path, System.Drawing.Imaging.ImageFORMat.Jpeg);
else
img.Save(_path, System.Drawing.Imaging.Imageformat.Gif);
m.Close();
return uploadpath + imgname;
}
catch (Exception ex)
{
return ex.Message;
}
}
public static string CreateIDCode()
{
dateTime Time1 = DateTime.Now.ToUniversaltime();
DateTime Time2 = Convert.ToDateTime("1970-01-01");
TimeSpan span = Time1 - Time2; //span就是两个日期之间的差额
string t = span.TotalMilliseconds.toString("0");
return t;
}
在php网站开发中,文件上传功能时常用到,之前我已介绍过如何利用PHP实现文件上传功能。随着WEB技术的发展,用户体验成为衡量网站成功与否的关键,今天和大家分享如何在PHP中利用jquery实现Ajax方式文件上传功能的例子,其中使用到了jQuery插件Ajaxupload,其可以实现单个文件和多文件上传功能。
AjaxUpload
jquery插件AjaxUpload实现文件上传功能时无需创建Form表单,即可实现Ajax方式的文件上传,当然根据需要也可以创建form表单。
准备工作
1、下载JQuery开发包和文件上传插件AjaxUpload。
2、创建uploadfile.HTML,并引入Jquery开发包和AjaxUpload插件
<script src="js/jquery-1.3.js"></script> <script src="js/ajaxupload.3.5.js"></script>
3、根据Jquery插件AjaxUpload的需要,创建一个触发Ajax文件上传功能的DIV
<ul> <li id="example"> <div id="upload_button">文件上传</div> <p>已上传的文件列表:</p> <ol class="files"></ol> </ul>
注释:由下面的代码我们可以看到Jquery插件AjaxUpload是根据upload_button这个DIV触发文件上传功能。
前台JS代码
在代码中我设置了开关,根据需要可以匹配上传文件类型,同时也可以设置是以Ajax方式实现单个文件上传还是多个文件上传。
$(document).ready(function(){
var button = $('#upload_button'), interval;
var fileType = "all",fileNum = "one";
new AjaxUpload(button,{
action: 'do/uploadfile.php',
/*data:{
'buttoninfo':button.text()
},*/
name: 'userfile',
onSubmit : function(file, ext){
if(fileType == "pic")
{
if (ext && /^(jpg|png|jpeg|gif)$/.test(ext)){
this.setData({
'info': '文件类型为图片'
});
} else {
$('<li></li>').AppendTo('#example .files').text('非图片类型文件,请重传');
return false;
}
}
button.text('文件上传中');
if(fileNum == 'one')
this.disable();
interval = window.setInterval(function(){
var text = button.text();
if (text.length < 14){
button.text(text + '.');
} else {
button.text('文件上传中');
}
}, 200);
},
onComplete: function(file, response){
if(response != "success")
alert(response);
button.text('文件上传');
window.clearInterval(interval);
this.enable();
if(response == "success");
$('<li></li>').appendTo('#example .files').text(file);
}
});
});
注释:
第1行:$(document).ready()函数,Jquery中的函数,类似于window.load,使用这个函数可在DOM载入就绪能够读取并操纵时立即调用绑定的函数。
第3行:fileType和fileNum参数代表上传文件的类型和数量,默认值为可上传所有类型文件,同一时间只能上传一个文件,如想上传图片文件或同时上传多个文件,可将这两个变量值变为pic和more。
第6~8行:POST到服务器的数据,你可以设置静态值也可以通过Jquery的dom操作函数获得一些动态值,比如form表单中INPUT的值等。
第9行:等同于前端
<input type="file" name="userfile">
服务器端$_FILES['userfile']
第10~36行:文件上传前触发的功能。
第11~21行:图片文件类型的过滤功能,Jquery setData函数用来设置POST至服务器端的值。
第25~26行:设置同时只上传一个文件还是多个文件,如果只上传一个文件,则将触发按钮禁掉。如果要多传输几个文件,请在服务器端PHP文件上传程序中设置MAXSIZE的值,当然上传文件的大小限制同时和PHP.INI文件中的设置也有关。
第28~35行:在文件上传过程中每隔200毫秒动态更新一次按钮的文字,已实现动态提示的效果。window.setinterval函数用来每隔指定的时间就执行一次内置的函数,交互时间单位为豪秒。
第37~49行:文件上传功能完成后触发的功能,根据返回值如果服务器端报错,则前端通过ALERT方式提示出错信息。
服务器端PHP文件上传代码
大体上是根据之前介绍的PHP文件上传功能代码实例教程改编,涉及到的文件上传大小的设置,出错信息等说明都已在此文中详细说明。
$upload_dir = '../file/';
$file_path = $upload_dir . $_FILES['userfile']['name'];
$MAX_SIZE = 20000000;
echo $_POST['buttoninfo'];
if(!is_dir($upload_dir))
{
if(!mkdir($upload_dir))
echo "文件上传目录不存在并且无法创建文件上传目录";
if(!chmod($upload_dir,0755))
echo "文件上传目录的权限无法设定为可读可写";
}
if($_FILES['userfile']['size']>$MAX_SIZE)
echo "上传的文件大小超过了规定大小";
if($_FILES['userfile']['size'] == 0)
echo "请选择上传的文件";
if(!move_uploaded_file( $_FILES['userfile']['tmp_name'], $file_path))
echo "复制文件失败,请重新上传";
switch($_FILES['userfile']['error'])
{
case 0:
echo "success" ;
break;
case 1:
echo "上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值";
break;
case 2:
echo "上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值";
break;
case 3:
echo "文件只有部分被上传";
break;
case 4:
echo "没有文件被上传";
break;
}
总结
基本上前端Ajax文件上传触发功能和服务器端PHP文件上传功能的原型就介绍完毕了,你可以根据自身需要对前后端代码进行补充,也可以将一些功能独立出来,比如文件类型、单个文件或者多文件上传功能。总的来说Jquery插件AjaxUpload实现文件上传功能的应用还是比较容易的。
相关推荐
- jQuery插件支持同一页面被多次调用 - Web前端
- jQuery实现的文字hover颜色渐变效果实例 - Web前端
- jQuery实现伪分页的方法分享 - Web前端
- 基于jquery实现下拉框美化特效 - Web前端
- jquery采用oop模式class类的使用示例 - Web前端
- jquery拖拽效果完整实例(附demo源码下载) - Web前端
- 基于HTML+CSS,jQuery编写的简易计算器后续(添加了键盘监听) - Web前端
- jQuery插件之jQuery.Form.js用法实例分析(附demo示例源码) - Web前端
- jQuery中hover与mouseover和mouseout的区别分析 - Web前端
- jQuery移动web开发之页面跳转和加载外部页面的实现 - Web前端
- 网页前端技术排行
-
- 1[Web前端]用javascript实现默认图片替代未显示的图片 - Web前端
- 2分析Iconfont-阿里巴巴矢量常用图标库 - Web前端
- 3jQuery实例教程:制作网页中可折叠的面板 - Web前端
- 4【第六章】Foundation之按钮和下拉功能 - Web前端
- 5基于jquery的滚动条滚动固定div(附演示下载) - Web前端
- 6jQuery编写widget的一些技巧分享 - Web前端
- 7分享精心挑选的12款优秀jQuery Ajax分页插件和教程 - Web前端
- 8jQuery实现鼠标移到元素上动态提示消息框效果 - Web前端
- 9在Mac/PC上远程调试iPhone/iPad上的网页 - Web前端
- 最近发表
-
- WordPress随机显示特色图片插件:Random Post Thumbnails
- KeePass实现Chrome浏览器自动填充密码方法一
- LNMP一键包nginx 301强制跳转到https教程
- KeePass实现Chrome浏览器自动填充密码方法二
- #建站# 免费的VPS管理软件Xshell8/Xftp8中文版下载
- 使用Xshell 8连接VPS教程_电脑登录vps的方法
- WordPress评论界面添加烟花????效果
- 不同浏览器书签同步方案:坚果云+Floccus_详细使用教程
- iOS端KeePassXC客户端APP:Strongbox Password Safe
- 给WordPress评论中的Gravatar头像图片添加ALT属性


