jQuery AjaxUpload 上传图片代码

前端技术 2023/09/02 JavaScript

本次使用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实现文件上传功能的应用还是比较容易的。

本文地址:https://www.stayed.cn/item/4602

转载请注明出处。

本站部分内容来源于网络,如侵犯到您的权益,请 联系我

我的博客

人生若只如初见,何事秋风悲画扇。