使用 Jquery AjaxUpload 上传图片
原文地址为: 使用 Jquery AjaxUpload 上传图片
来源:http://www.cnblogs.com/hxling/archive/2010/07/05/1771320.html
本次使用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; }
.
.
.
来源:http://www.leapsoul.cn/?p=304
在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实现文件上传功能的应用还是比较容易的。
注:PHP网站开发教程-leapsoul.cn版权所有,转载时请以链接形式注明原始出处及本声明,谢谢。
.
.
.
来源:http://hi.baidu.com/spurringworld/blog/item/adb09b341d670ad0a2cc2bf6.html
引入js文件 - ajaxupload.js
引入java jar文件 - commons-fileupload-1.2.1.jar;commons-io-1.4.jar
上传js代码
//upload resumenew AjaxUpload('resume', { // Location of the server-side upload script // NOTE: You are not allowed to upload files to another domain action: '../resources/Reg1C/upload', // File upload name name: 'resume', // Fired after the file is selected // Useful when autoSubmit is disabled // You can return false to cancel upload // @param file basename of uploaded file // @param extension of that file onChange: function (file, extension) { }, // Fired before the file is uploaded // You can return false to cancel upload // @param file basename of uploaded file // @param extension of that file onSubmit: function (file, extension) { if (!(extension && /^(doc|docx|pdf)$/i.test(extension))) { // extension is not allowed alert('Error: invalid file extension'); // cancel upload return false; } // allow only 1 upload //this.disable(); }, // Fired when file upload is completed // WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE! // @param file basename of uploaded file // @param response server response onComplete: function (file, response) { if ($(response).find("isSuccess").text() == "false") { alert($(response).find("msg").text()); if ($(response).find("id").text() == "-1") { window.location.href = "../Home/index.jsp"; } return; } else { $("#uploadMsg").html(file + " is uploaded!"); } }});
Java code: (RESTful )
@POST@Path("upload")@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public ResponseVO upload() throws IOException {ResponseVO responseVO = new ResponseVO();Integer userId = SessionStoreManager.getUserId(request);if (userId == null) {responseVO.setId(ResponseVO.HOME_ALERT);responseVO.setMsg("Your session is time out!");return responseVO;}try {// Create a factory for disk-based file itemsFileItemFactory factory = new DiskFileItemFactory();// Create a new file upload handlerServletFileUpload upload = new ServletFileUpload(factory);// Parse the requestList<FileItem> items = upload.parseRequest(request);
// Process the uploaded itemsIterator<FileItem> iter = items.iterator();while (iter.hasNext()) {FileItem item = iter.next();// Process a file uploadif (!item.isFormField()) {String fileName = item.getName();//comment out for .docx type will get a too long stringString contentType = item.getContentType();if (!(Resume.PDF_CONTENT_TYPE.equals(contentType)|| Resume.DOC_CONTENT_TYPE.equals(contentType)|| Resume.DOCX_CONTENT_TYPE.equals(contentType))) {responseVO.setIsSuccess(false);responseVO.setMsg("MS Word or PDF files only.");return responseVO;}long sizeInBytes = item.getSize();if (sizeInBytes > Constants.MAX_RESUME_SIZE) {responseVO.setIsSuccess(false);responseVO.setMsg("Error uploading the resume file. Resume file size must be less than 1M.");return responseVO;}byte[] data = item.get();//Expert entityExpert = em.find(Expert.class, userId);Resume entityResume = em.find(Resume.class, userId);if (entityResume == null) {entityResume = new Resume();entityResume.setId(userId);em.persist(entityResume);}entityResume.setContent(data);entityResume.setContentType(contentType);
responseVO.setIsSuccess(true);responseVO.setMsg("Upload sucess!" + item.getContentType());}}} catch (Exception e) {responseVO.setIsSuccess(false);responseVO.setMsg("Upload failed!");}
return responseVO;}
转载请注明本文地址: 使用 Jquery AjaxUpload 上传图片
使用 Jquery AjaxUpload 上传图片相关推荐
- jquery实现上传图片及图片大小验证、图片预览效果代码
jquery实现上传图片及图片大小验证.图片预览效果代码 jquery实现上传图片及图片大小验证.图片预览效果代码 上传图片验证 */ function submit_upload_picture() ...
- php结合jquery异步上传图片(ajaxSubmit)
2019独角兽企业重金招聘Python工程师标准>>> php结合jquery异步上传图片(ajaxSubmit),以下为提交页面代码: <!DOCTYPE html PUBL ...
- MVC中使用jquery uploadify上传图片报302错误
使用jquery uploadify上传图片报302错误研究了半天,发现我上传的action中有根据session判断用户是否登录,如果没有登录就跳到登陆页,所以就出现了302跳转错误.原来更新了fl ...
- jquery php 异步图片上传实例,php结合jquery异步上传图片(ajaxSubmit)
Ajax异步上传图片 functionsky_upfiles(){varmesstxt; $("#sky_upform").ajaxSubmit({//dataType:'scri ...
- jQuery 的上传图片预览插件
插件代码: view plaincopy to clipboardprint? 01.(function($) { 02. $.fn.PreviewImage = function(opti ...
- jquery批量上传图片 java_简单多图片上传 jquery+java 代码
/** 添加歌曲 */ function addSong(){ var id=$("#_activity_id").val(); window.location.href = &q ...
- jQuery实现上传图片的预览
在html中: <form id="certForm" method="post" enctype="multipart/form-data&q ...
- php上传图片大小判断,jQuery实现判断上传图片类型和大小的方法示例
本文实例讲述了jQuery实现判断上传图片类型和大小的方法.分享给大家供大家参考,具体如下: 这里使用jQuery判断上传图片的类型和大小: 图片格式为: 图片大小为: $(function(){ v ...
- php ci 处理图片 裁剪,jquery.form + Jcrop + CI框架实现图片裁剪上传
功能: 1.通过jquery.form上传图片,并按一定比例显示预览图. 2.通过Jcrop裁剪图片,并显示裁剪预览图 3.通过CI的图像处理类保存剪切后图片 问题: 1.通过jquery.form来 ...
最新文章
- python 之 pip、pypdf2 安装与卸载
- Kettle 合并记录报错!
- boost::core_numbers用法的测试程序
- 软件项目风险评估报告00
- [leedcode][409][java]
- react 消息订阅-发布机制(解决兄弟组件通信问题)
- 阿里程序员深夜智救31楼跳楼邻居
- python设置本机IP地址、子网掩码、DNS,获取本机IP地址、子网掩码、DNS、MAC
- python 函数式_10分钟学习函数式Python
- 在asp中实现自动缩放图片(推荐)
- linux运行火车头采集,网站抓取精灵火车采集器如何定时自动运行?
- OpenG 分化基础知识
- 一键怎样批量修改图片像素大小
- Android 一个改善的okHttp封装库
- python爬虫 网页表格
- 手机怎么做个人简历?多行业简历模板自由选择
- 服务监控--zabbix
- 如何用 CSS 实现三角形
- dinic 最大流费用流模板
- 高效地分析Android内存--MAT工具解析
热门文章
- 20201120翻译_disba基于Python的面波正演模拟程序包
- 斧子演示(AxeSlide):新时期,新用法
- 【网页设计自习室#002】网站页面基本布局与结构
- 起来!不愿做奴隶的“张江男”
- php用户注销代码,php注销代码(session注销)
- python错误与异常(try/except 和 try/except...else)
- java开发微信如何维护登录状态_5.13微信登录维护态与获取用户信息思想
- ava并发学习之二:线程池
- 大创项目部分笔记(1)
- Photoshop插件-秋色效果-脚本开发-PS插件