先前 写过 JS 判断上传 文件 大小 后来发现一个问题, 就是单页面运行 js 没有问题, 但是基础呢个到项目中 有些时候 obj_img.dynsrc = file.value; 报错说没有 权限访问. 所以实在没有办法来获取客服端 上传 文件的大小。 于是就把文件post到服务端来获取大小了。

官方的ajaxfileupload只能上传一个文件,这里简单修改一下可以上传多个 文件, 修改后的 code 如下:

jQuery.extend({
createUploadIframe: function (id, uri) {//id为当前系统时间字符串,uri是外部传入的json对象的一个参数
//create frame
var frameId = 'jUploadFrame' + id; //给iframe添加一个独一无二的id
var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"'; //创建iframe元素
if (window.ActiveXObject) {//判断浏览器是否支持ActiveX控件
if (typeof uri == 'boolean') {
iframeHtml += ' src="' + 'javascript:false' + '"';
} else if (typeof uri == 'string') {
iframeHtml += ' src="' + uri + '"';
}
}
iframeHtml += ' />';
jQuery(iframeHtml).appendTo(document.body); //将动态iframe追加到body中
return jQuery('#' + frameId).get(0); //返回iframe对象
},
createUploadForm: function (id, fileElementIds, data) {//id为当前系统时间字符串,fileElementIds为页面<input type='file' />的id集合,datas的值需要根据传入json的键来决定
//create form
var formId = 'jUploadForm' + id; //给form添加一个独一无二的id
var fileId = 'jUploadFile' + id; //给<input type='file' />添加一个独一无二的id
var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data" ></form>'); //创建form元素
if (data) {//通常为false
for (var i in data) {
jQuery('<input type="hidden" name="' + i.toString() + '" value="' + data[i] + '" />').appendTo(form); //根据data的内容,创建隐藏域
}
}
for (var i = 0; i < fileElementIds.length; i++) {
var fileElementId = fileElementIds[i];
var oldElement = jQuery('#' + fileElementId); //得到页面中的<input type='file' />对象
var newElement = jQuery(oldElement).clone(); //克隆页面中的<input type='file' />对象
jQuery(oldElement).attr('id', fileId+i.toString()); //修改原对象的id
jQuery(oldElement).before(newElement); //在原对象前插入克隆对象
jQuery(oldElement).appendTo(form); //把原对象插入到动态form的结尾处
} //set attributes
jQuery(form).css('position', 'absolute'); //给动态form添加样式,使其浮动起来,
jQuery(form).css('top', '-1200px');
jQuery(form).css('left', '-1200px');
jQuery(form).appendTo('body'); //把动态form插入到body中
return form;
},
ajaxFileUpload: function (s) {//这里s是个json对象,传入一些ajax的参数
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s); //此时的s对象是由jQuery.ajaxSettings和原s对象扩展后的对象
var id = new Date().getTime(); //取当前系统时间,目的是得到一个独一无二的数字
var form = jQuery.createUploadForm(id, s.fileElementIds, (typeof (s.data) == 'undefined' ? false : s.data)); //创建动态form
var io = jQuery.createUploadIframe(id, s.secureuri); //创建动态iframe
var frameId = 'jUploadFrame' + id; //动态iframe的id
var formId = 'jUploadForm' + id; //动态form的id
// Watch for a new set of requests
if (s.global && !jQuery.active++) {//当jQuery开始一个ajax请求时发生
jQuery.event.trigger("ajaxStart"); //触发ajaxStart方法
}
var requestDone = false; //请求完成标志
// Create the request object
var xml = {};
if (s.global)
jQuery.event.trigger("ajaxSend", [xml, s]); //触发ajaxSend方法
// Wait for a response to come back
var uploadCallback = function (isTimeout) {//回调函数
var io = document.getElementById(frameId); //得到iframe对象
try {
if (io.contentWindow) {//动态iframe所在窗口对象是否存在
xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null;
xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document;
} else if (io.contentDocument) {//动态iframe的文档对象是否存在
xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null;
xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document;
}
} catch (e) {
jQuery.handleError(s, xml, null, e);
} if (xml || isTimeout == "timeout") {//xml变量被赋值或者isTimeout == "timeout"都表示请求发出,并且有响应
requestDone = true; //请求完成
var status; try {
status = isTimeout != "timeout" ? "success" : "error"; //如果不是“超时”,表示请求成功
// Make sure that the request was successful or notmodified
if (status != "error") { // process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData(xml, s.dataType); //根据传送的type类型,返回json对象,此时返回的data就是后台操作后的返回结果
// If a local callback was specified, fire it and pass it the data
if (s.success)
s.success(data, status); //执行上传成功的操作
// Fire the global callback
if (s.global)
jQuery.event.trigger("ajaxSuccess", [xml, s]);
} else
jQuery.handleError(s, xml, status);
} catch (e) {
status = "error";
jQuery.handleError(s, xml, status, e);
} // The request was completed
if (s.global)
jQuery.event.trigger("ajaxComplete", [xml, s]); // Handle the global AJAX counter
if (s.global && ! --jQuery.active)
jQuery.event.trigger("ajaxStop"); // Process result
if (s.complete)
s.complete(xml, status);
jQuery(io).unbind();//移除iframe的事件处理程序
setTimeout(function () {//设置超时时间
try {
jQuery(io).remove();//移除动态iframe
jQuery(form).remove();//移除动态form
} catch (e) {
jQuery.handleError(s, xml, null, e);
}
}, 100)
xml = null
}
} // Timeout checker
if (s.timeout > 0) {//超时检测
setTimeout(function () { // Check to see if the request is still happening
if (!requestDone) uploadCallback("timeout");//如果请求仍未完成,就发送超时信号
}, s.timeout);
} try {
var form = jQuery('#' + formId);
jQuery(form).attr('action', s.url);//传入的ajax页面导向url
jQuery(form).attr('method', 'POST');//设置提交表单方式
jQuery(form).attr('target', frameId);//返回的目标iframe,就是创建的动态iframe
if (form.encoding) {//选择编码方式
jQuery(form).attr('encoding', 'multipart/form-data');
} else {
jQuery(form).attr('enctype', 'multipart/form-data');
}
jQuery(form).submit();//提交form表单
} catch (e) {
jQuery.handleError(s, xml, null, e);
}
jQuery('#' + frameId).load(uploadCallback); //ajax 请求从服务器加载数据,同时传入回调函数
return { abort: function () { } };
},
uploadHttpData: function (r, type) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText; // If the type is "script", eval it in global context
if (type == "script")
jQuery.globalEval(data); // Get the JavaScript object, if JSON is used.
if (type == "json")
eval("data = " + data); // evaluate scripts within html
if (type == "html")
jQuery("<div>").html(data).evalScripts(); return data;
}
})

调用示例:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="jquery-1.7.1.js" type="text/javascript"></script>
<script src="ajaxfileupload2.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$(":button").click(function () {
ajaxFileUpload();
})
})
function ajaxFileUpload() {
$.ajaxFileUpload
(
{
url: '/upload.aspx', //用于文件上传的服务器端请求地址
secureuri: false, //一般设置为false
fileElementIds: ['file1', 'file2', 'file3', 'file4'], //文件上传空间的id属性 <input type="file" id="file" name="file" />
data: { file1DataSize: 0, file12DataSize: 0, file3DataSize: 0, file4DataSize: 0 },//可选属性, 一般和fileElementIds个数 相同
dataType: 'json', //返回值类型 一般设置为json
success: function (data, status) //服务器成功响应处理函数
{
//$("#img1").attr("src", data.imgurl);
//if (typeof (data.error) != 'undefined') {
// if (data.error != '') {
// alert(data.error);
// } else {
// alert(data.msg);
// }
//}
alert(data[0].DataSize);
},
error: function (data, status, e)//服务器响应失败处理函数
{
alert(e);
}
}
)
return false;
}
</script>
</head>
<body>
<p><input type="file" id="file1" name="file" /></p>
<p><input type="file" id="file2" name="file" /></p>
<p><input type="file" id="file3" name="file" /></p>
<p><input type="file" id="file4" name="file" /></p>
<input type="button" value="上传" />
<p><img id="img1" alt="" src="" /></p>
</body>
</html>
using System;
using System.Collections.Generic; using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
namespace jQueryAJAXFileUpload
{
public partial class upload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
HttpFileCollection files = Request.Files;//这里只能用<input type="file" />才能有效果,因为服务器控件是HttpInputFile类型
if (files.Count > )
{
string res = "";
for (int i = ; i < files.Count; i++)
{
if (files[i].ContentLength > )
{
var item = files[i];
string postData = string.Empty;
string key = "file" + (i + ).ToString() + "DataSize";
postData = Request.Form[key]; string newfilePath = Server.MapPath("/") + System.IO.Path.GetFileName(item.FileName);
if (File.Exists(newfilePath))
{
File.Delete(newfilePath);
}
item.SaveAs(newfilePath);
string msg = " 成功! 文件大小为:" + item.ContentLength;
if(res.Length>)
{
res+=",";
}
res += "{ PostData:'" + postData + "', msg:'" + msg + "',DataSize:'" + item.ContentLength + "'}";
}
}
Response.Write("["+res+"]");
Response.End();
}
}
}
}

ajax file upload 修改的更多相关文章

  1. jquery ajax file upload NET MVC 无刷新文件上传

    网上有各种各样的文件上传方法,有基于JS框架的.也有基于flash swf插件的. 这次分享一个比较简单而且实用能快速上手的文件上传方法,主要步骤: 1.引用Jquery包,我用的是jquery-1. ...

  2. JQuery File Upload 插件 出现 “empty file upload result” 错误的解决方案。

    本例中采用的是 JQuery File Upload + ASP.NET 的方式, Google了大半天基本没有找到合理的解决方案,倒是在 NodeJS的一遍博客中找到了灵感:http://www.i ...

  3. html5 file upload and form data by ajax

    html5 file upload and form data by ajax 最近接了一个小活,在短时间内实现一个活动报名页面,其中遇到了文件上传. 我预期的效果是一次ajax post请求,然后在 ...

  4. jquery ajax发送delete(use in jquery file upload delete file)

    环境: jQuery file upload HTML example code <div class="pic-preview"> <div class=&qu ...

  5. jQuery File Upload 单页面多实例的实现

    jQuery File Upload 的 GitHub 地址:https://github.com/blueimp/jQuery-File-Upload 插件描述:jQuery File Upload ...

  6. 上传文件 file upload 学习笔记

    这里我只会说说一些完成 file upload 的基础 API. 很多项目我们需要上传文件. 有简单的 input file, 有需要验证的,有需要压缩的(img),有需要分段的(video),有需要 ...

  7. jQuery File Upload blueimp with struts2 简单试用

    Official Site的话随便搜索就可以去了 另外新版PHP似乎都有问题  虽然图片都可以上传  但是response报错  我下载的是8.8.7木有问题   但是8.8.7版本结合修改main. ...

  8. jQuery File Upload 图片上传解决方案兼容IE6+

    1.下载:https://github.com/blueimp/jQuery-File-Upload 2.命令: npm install bower install ================= ...

  9. jquery file upload + asp.net 异步多文件上传

    百度了很久,国内一直 找不到 使用jquery file upload 插件 +asp.net 的相关代码 一开始使用 jquery uploadify ,一款基于 flash的插件,但是不支持 Sa ...

随机推荐

  1. java中Optional和Stream流的部分操作

    package test9; import java.util.DoubleSummaryStatistics; import java.util.Optional; import java.util ...

  2. 苹果Mac OS 显示隐藏文件

    苹果Mac OS 操作系统下,隐藏文件默认为隐藏状态,隐藏文件是否显示有多种方法可以设置. 方法一: 打开终端,输入命令行 显示Mac隐藏文件的命令: defaults write com.apple ...

  3. BZOJ.4939.[Ynoi2016]掉进兔子洞(莫队 bitset 分组询问)

    BZOJ 洛谷 删掉的数即三个区间数的并,想到bitset:查多个区间的数,想到莫队. 考虑bitset的每一位如何对应每个数的不同出现次数.只要离散化后不去重,每次记录time就可以了. 但是如果对 ...

  4. 编译 php-memcache 扩展时提示Cannot find autoconf

    下载memcache扩展 http://pecl.php.net/package/memcache ,到 /usr/local/src目录下并解压 [root@bogon src]# .tgz [ro ...

  5. Dell H300/6i/6iR/H700/H800阵列卡配置(转)

    说明:其实Dell系列的阵列卡基本都是同一个套路和界面,包括操作步骤,不同的是不同的卡性能和支持Raid模式不一样而已. 名称解释: Disk Group:磁盘组,这里相当于是阵列,例如配置了一个RA ...

  6. 实现DIV层内的文字垂直居中(转)

    有时候,为了网页设计的美观,需要把div+css设计的页面里的某些div层里的文字垂直居中,包括多行文字以及单行文字:方法有不少,但真正能实现而代码又简洁的介绍不多,flymorn就为大家介绍几种适用 ...

  7. CENTOS下搭建SVN服务器(转)

    1.安装svn yum install -y subversion 2.验证安装是否成功 svnserve --version 3.创建svn版本库 mkdir svn svnadmin create ...

  8. spring Quartz基于配置文件和注解的实现

    这里仅仅是做简单的记录怎样实现. 一.基于配置文件的实现 ①编写须要调度的类 package com.study; import org.springframework.scheduling.anno ...

  9. UINavigationController 、UINavigationBar 、UINavigationItem 超清晰直观详解

    UINavigationController 部分 1. UINavigationController 是一个容器类.里面盛放的是UIViewController. 容器的意思是,如果你不放入UIVi ...

  10. C#编程(六十三)----------并行LINQ

    并行LINQ .NET4在System.Linq命名空间中包含一个新类ParallelEnumerable,可以分解查询的工作使其分布在多个线程上.尽管Enumerable类给IEnumerable& ...