ajax上传⽂件,并检查⽂件类型、检查⽂件⼤⼩1、使⽤ajaxfileupload.js的插件,但是对插件做了⼀处修改,才能够正常使⽤
修改的部分如下:
1 2 uploadHttpData: function (r, type) {
3 var data = !type;
4 data = type == "xml" || data ? r.responseXML : r.responseText; // If the type is "script", eval it in global context
5 if (type == "script")
6 jQuery.globalEval(data); // Get the JavaScript object, if JSON is used.
7 if (type == "json"){//对json类型的返回结果,做截取处理
8 var tempData = data.substring(data.indexOf(">\"") + 2);
9 data = place("\"</pre>", "");
10 }
11 if (type == "html")
12 jQuery("<div>").html(data).evalScripts();
13 return data;
14 }
2、检查⽂件⼤⼩,对于常⽤浏览器测试都是可以的...
3、使⽤struts的action接收,两个参数:1)上传到⽂件imageFile;2)上传的本地⽂件路径imageFilePath
4、ajaxfileupload.js源码在最后贴出来
1<!DOCTYPE html>
2<html>
3<head>
4<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
5<script src="jquery1.8/jquery-1.8.0.js" type="text/javascript"></script>
6<script src="ajaxfileupload.js"></script>
7<script type="text/javascript">
8
9/* 头像上传 */
10function ajaxfileupload() {
11var filepath = $("#imageFile").val();
12//检查是否为图⽚
13if(!isImage(filepath)){
14return false;
15 }
json检查16//检查⽂件⼤⼩,不能超过2M
17if(!checkFileSize(filepath)){
18return false;
19 }
20
21 $.ajaxFileUpload({
22 url: 'stu/uploadimage',
23 secureuri: false, //⼀般设置为false
24 type: 'post',
25 data: {imageFileName: $("#imageFile").val()},
26 dataType: 'json',
27 fileElementId: "imageFile",
28 success: function (data, status) {
29if (data == "error") {
30 alert("上传失败,请重试");
31 } else {
32//导航栏:头像
33 $("#header_student_image").attr("src", data);
34 alert("上传成功");
35 }
36 },
37 error: function (data, status, e)//服务器响应失败处理函数
38 {
39 alert("上传失败,请重试");
40 }
41 }
42 );
43return false;
44 };
45
46/* 检查是否为图⽚ */
47function isImage(filepath) {
48var extStart = filepath.lastIndexOf(".");
49var ext = filepath.substring(extStart, filepath.length).toUpperCase();
50if (ext != ".BMP" && ext != ".PNG" && ext != ".GIF" && ext != ".JPG" && ext != ".JPEG") {
51 alert("头像只能是bmp,png,gif,jpeg,jpg格式喔");
52return false;
53 }
54return true;
55 }
56
57/* 检查图⽚⼤⼩,不能超过3M,⽀持IE、filefox、chrome */
58function checkFileSize(filepath) {
59var maxsize = 2 * 1024 * 1024;//2M
60var errMsg = "上传的头像⽂件不能超过2M喔";
61var tipMsg = "您的浏览器暂不⽀持上传头像,确保上传⽂件不要超过2M,建议使⽤IE、FireFox、Chrome浏览器。";
62
63try {
64var filesize = 0;
65var ua = window.navigator.userAgent;
66if (ua.indexOf("MSIE") >= 1) {
67//IE
68var img = new Image();
69 img.src = filepath;
70 filesize = img.fileSize;
71 } else {
72//file_size = ElementById("imageFile").files[0].size;
73 filesize = $("#imageFile")[0].files[0].size; //byte
74 }
75
76if (filesize > 0 && filesize > maxsize) {
77 alert(errMsg);
78return false;
79 } else if (filesize == -1) {
80 alert(tipMsg);
81return false;
82 }
83 } catch (e) {
84 alert("头像上传失败,请重试");
85return false;
86 }
87return true;
88 }
89</script>
90<title>test:上传头像</title>
91</head>
92<body>
93<table width="500" cellspacing="0" cellpadding="0">
94<tr>
95<td width="72" id="fileType">
96</td>
97<td width="242">
98<img id="image_url" src="" class="wetalkimg"/>
99<input type="file" id="imageFile" name="imageFile" onchange="ajaxfileupload(this);"/>
100</td>
101</tr>
102</table>
103</body>
104</html
5、ajaxfileupload.js源码
d({
2 createUploadIframe: function (id, uri) {//id为当前系统时间字符串,uri是外部传⼊的json对象的⼀个参数
3//create frame
4var frameId = 'jUploadFrame' + id; //给iframe添加⼀个独⼀⽆⼆的id
5var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" '; //创建iframe元素
6if (window.ActiveXObject) {//判断浏览器是否⽀持ActiveX控件
7if (typeof uri == 'boolean') {
8 iframeHtml += ' src="' + 'javascript:false' + '"';
9 } else if (typeof uri == 'string') {
10 iframeHtml += ' src="' + uri + '"';
11 }
12 }
13 iframeHtml += ' />';
14 jQuery(iframeHtml).appendTo(document.body); //将动态iframe追加到body中
15return jQuery('#' + frameId).get(0); //返回iframe对象
16 },
17 createUploadForm: function (id, fileElementId, data) {//id为当前系统时间字符串,fileElementId为页⾯<input type='file' />的id,data的值需要根据传⼊json的键来决定
18//create form
19var formId = 'jUploadForm' + id; //给form添加⼀个独⼀⽆⼆的id
20var fileId = 'jUploadFile' + id; //给<input type='file' />添加⼀个独⼀⽆⼆的id
21var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data" ></form>'); //创建form元素
22if (data) {//通常为false
23for (var i in data) {
24 jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form); //根据data的内容,创建隐藏域,这部分我还不知道是什么时候⽤到。估计是传⼊json的时候,如果默认传⼀些参数的话要⽤到。
25 }
26 } var oldElement = jQuery('#' + fileElementId); //得到页⾯中的<input type='file' />对象
27var newElement = jQuery(oldElement).clone(); //克隆页⾯中的<input type='file' />对象
28 jQuery(oldElement).attr('id', fileId); //修改原对象的id
29 jQuery(oldElement).before(newElement); //在原对象前插⼊克隆对象
30 jQuery(oldElement).appendTo(form); //把原对象插⼊到动态form的结尾处
31//set attributes
32 jQuery(form).css('position', 'absolute'); //给动态form添加样式,使其浮动起来,
33 jQuery(form).css('top', '-1200px');
34 jQuery(form).css('left', '-1200px');
35 jQuery(form).appendTo('body'); //把动态form插⼊到body中
36return form;
37 },
38 ajaxFileUpload: function (s) {//这⾥s是个json对象,传⼊⼀些ajax的参数
39// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
40 s = d({}, jQuery.ajaxSettings, s); //此时的s对象是由jQuery.ajaxSettings和原s对象扩展后的对象
41var id = new Date().getTime(); //取当前系统时间,⽬的是得到⼀个独⼀⽆⼆的数字
42var form = ateUploadForm(id, s.fileElementId, (typeof (s.data) == 'undefined' ? false : s.data)); //创建动态form
43var io = ateUploadIframe(id, s.secureuri); //创建动态iframe
44var frameId = 'jUploadFrame' + id; //动态iframe的id
45var formId = 'jUploadForm' + id; //动态form的id
46// Watch for a new set of requests
47if (s.global && !jQuery.active++) {//当jQuery开始⼀个ajax请求时发⽣
48 igger("ajaxStart"); //触发ajaxStart⽅法
49 } var requestDone = false; //请求完成标志
50// Create the request object
51var xml = {}; if (s.global)
52 igger("ajaxSend", [xml, s]); //触发ajaxSend⽅法
53// Wait for a response to come back
54var uploadCallback = function (isTimeout) {//回调函数
55var io = ElementById(frameId); //得到iframe对象
56try { if (io.contentWindow) {//动态iframe所在窗⼝对象是否存在
57 sponseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null;
58 sponseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document;
59 } else if (io.contentDocument) {//动态iframe的⽂档对象是否存在
60 sponseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null;
61 sponseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document;
62 }
63 } catch (e) {
64 jQuery.handleError(s, xml, null, e);
65 } if (xml || isTimeout == "timeout") {//xml变量被赋值或者isTimeout == "timeout"都表⽰请求发出,并且有响应
66 requestDone = true; //请求完成
67var status; try {
68 status = isTimeout != "timeout" ? "success" : "error"; //如果不是“超时”,表⽰请求成功
69// Make sure that the request was successful or notmodified
70if (status != "error") { // process the data (runs the xml through httpData regardless of callback)
71var data = jQuery.uploadHttpData(xml, s.dataType); //根据传送的type类型,返回json对象,此时返回的data就是后台操作后的返回结果
72// If a local callback was specified, fire it and pass it the data
73if (s.success)
74 s.success(data, status); //执⾏上传成功的操作
75// Fire the global callback
76if (s.global)
77 igger("ajaxSuccess", [xml, s]);
78 } else
79 jQuery.handleError(s, xml, status);
80 } catch (e) {
81 status = "error";
82 jQuery.handleError(s, xml, status, e);
83 } // The request was completed
84if (s.global)
85 igger("ajaxComplete", [xml, s]); // Handle the global AJAX counter
86if (s.global && ! --jQuery.active)
87 igger("ajaxStop"); // Process result
88if (splete)
89 splete(xml, status);
90 jQuery(io).unbind();//移除iframe的事件处理程序
91 setTimeout(function () {//设置超时时间
92try {
93 jQuery(io).remove();//移除动态iframe
94 jQuery(form).remove();//移除动态form
95 } catch (e) {
96 jQuery.handleError(s, xml, null, e);
97 }
98 }, 100)
99 xml = null
100 }
101 } // Timeout checker
102if (s.timeout > 0) {//超时检测
103 setTimeout(function () { // Check to see if the request is still happening
104if (!requestDone) uploadCallback("timeout");//如果请求仍未完成,就发送超时信号
105 }, s.timeout);
106 } try { var form = jQuery('#' + formId);
107 jQuery(form).attr('action', s.url);//传⼊的ajax页⾯导向url
108 jQuery(form).attr('method', 'POST');//设置提交表单⽅式
109 jQuery(form).attr('target', frameId);//返回的⽬标iframe,就是创建的动态iframe
110if (ding) {//选择编码⽅式
111 jQuery(form).attr('encoding', 'multipart/form-data');
112 } else {
113 jQuery(form).attr('enctype', 'multipart/form-data');
114 }
115 jQuery(form).submit();//提交form表单
116 } catch (e) {
117 jQuery.handleError(s, xml, null, e);
118 }
119 jQuery('#' + frameId).load(uploadCallback); //ajax 请求从服务器加载数据,同时传⼊回调函数
120return { abort: function () { } };
121 },
122 uploadHttpData: function (r, type) {
123var data = !type;
124 data = type == "xml" || data ? r.responseXML : r.responseText; // If the type is "script", eval it in global context 125if (type == "script")
126 jQuery.globalEval(data); // Get the JavaScript object, if JSON is used.
127if (type == "json"){//修改之处
128var tempData = data.substring(data.indexOf(">\"") + 2);
129 data = place("\"</pre>", "");
130 }
131if (type == "html")
132 jQuery("<div>").html(data).evalScripts();
133return data;
134 },
135 handleError: function (s, xhr, status, e) {
136if (s.error) {
137 s.error.t || s, xhr, status, e);
138 }
139if (s.global) {
140 (s.context ? t) : jQuery.event).trigger("ajaxError", [xhr, s, e]);
141 }
142 }
143 })
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论