Javascript与asp.net 实现Ajax多文件无刷新上传


这几天在等着上班,闲来无事,就写了一个无刷新的上传功能,这个上传只是实现局部刷新,我已经把方法都整理好,可以随意添加多个上传控件,只要调用一个方法就可以了,为了便于阅读我没有把JS独立出来,以后真正用到项目上的时候再提出来,我在每个方法上面都写了注视,具体可以看代码部分,现在一直在用JQuery,它提供的方法太好用的,剩了很多事。
此方法主要是通过iFrame调用上传页的控件来实现的,具体请看下面的代码。





无刷新上传主要的HTML代码(upload.html):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<title>AjaxUpload</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript" src="scripts/interface.js"></script>
<style type="text/css" media="all">
*
{
    margin
:0;
    padding
:0;
}

img
{border:none;}

ul
{
    list-style-type
:none;
}

ul li
{
    padding
:2px 4px;
}

body
{
    font-family
: 宋体, 黑体,verdana, Arial;
    font-size
:12px;
    color
:#333;
    background
:#DDDDDD;
    margin
:30px;
    padding
:0;
}

.box
{
    border
:1px solid #CCC;
    background
:#FFF;
    padding
:8px;
    margin
:5px;
    clear
:both;
}

.title 
{
    background
:#F0F0F0;padding:5px;
    font-weight
:bold;
}

.tooltip
{
    background
:#F0F0F0;
    border-color
:#bbb;
}

.tooltip h1 
{
    color
:#A8DF00;
    font-family
: 微软雅黑,黑体,宋体,verdana, Arial;
}

.titlebutton
{
    float
:right;
}

.uploading
{
    background
:#FFF;
    color
:#444;
    text-align
:left;
    width
:500px;
    padding
:4px;
}

.image
{
    border
:1px solid #ddd;
    margin
:2px;
    padding
:1px;
    display
:inline;
    width
:300px;
}

.uploadcontrol 
{
    margin
:4px 0;
    border-bottom
:1px solid #F0F0F0;
}
</style>
<script type="text/javascript">
    
     $(document).ready(
function(){          
          
for(var i=0;i<5;i++)
          {
             uploadcreate($(
"#uploadbox"),i);
          }
    });
     
     
var hideDiv = function(idName){
         $(
"#"+idName).fadeOut("fast");
     };
     
     
//是否显示上传后的图片
     var isshowpic = true;  
     
var uploadshowpic = function(el){
         isshowpic 
= !(isshowpic);
         
if(isshowpic)
         {
             el.html(
"图片显示关闭");
         }
         
else
         {
             el.html(
"图片显示开启");
         }
     };
     
     
//载入中的GIF动画
    var loadingUrl = "images/ajax-loader.gif";
    
    
//选择文件后的事件,iframe里面调用的
    var uploading = function(imgsrc,itemid){
        
var el = $("#uploading"+itemid);
        $(
"#ifUpload"+itemid).fadeOut("fast");
        el.fadeIn(
"fast");
        el.html(
"<img src='"+loadingUrl+"' align='absmiddle' /> 上传中");
        
return el;
    };
    
    
//重新上传方法    
    var uploadinit = function(itemid){
        currentItemID 
++;
        $(
"#uploading"+itemid).fadeOut("fast",function(){
             $(
"#ifUpload"+itemid).fadeIn("fast");
             $(
"#panelViewPic"+itemid).fadeOut("fast");
        });
               
    };
    
    
//上传时程序发生错误时,给提示,并返回上传状态
    var uploaderror = function(itemid){
        alert(
"程序异常,"+itemid+"项上传未成功。");
        uploadinit();
    };
    
    
//上传成功后的处理
    var uploadsuccess = function(newpath,itemid){
        $(
"#uploading"+itemid).html("文件上传成功. <a href='javascript:void(0);' onclick='uploadinit("+itemid+");'>[重新上传]</a>");
        
if(isshowpic)
        {
            $(
"#panelViewPic"+itemid).html("<a href='"+newpath+"' title='点击查看大图' target='_blank'><img src='"+newpath+"' alt='' style='width:300px;' /></a>");        
            $(
"#panelViewPic"+itemid).fadeIn("fast");
        }
    };
    
    
    
var currentItemID = 0;  //用于存放共有多少个上传控件了
    //创建一个上传控件
    var uploadcreate = function(el,itemid){
        currentItemID 
++;
        
if(itemid == null)
        {
            itemid 
= currentItemID;
        }  
        
var strContent = "<div class='uploadcontrol'><iframe src=\"upload.aspx?id="+itemid+"\" id=\"ifUpload"+itemid+"\" frameborder=\"no\" scrolling=\"no\" style=\"width:400px; height:28px;\"></iframe>";
        strContent 
+= "<div class=\"uploading\" id=\"uploading"+itemid+"\" style=\"display:none;\" ></div>";
        strContent 
+= "<div class=\"image\" id=\"panelViewPic"+itemid+"\" style=\"display:none;\"></div></div>";
        el.append(strContent);
    };
     
</script>

</head>

<body>

<div id="tipbox" class="box tooltip">
    
<href="#" onclick="hideDiv('tipbox');">[关闭]</a>
    
<div class="content">
        
<h1>AjaxUpload - 多文件无刷新上传源代码 v1.0</h1>
        
<p>作者:李华顺 <href="http://huacn.cnblogs.com" target="_blank">http://huacn.cnblogs.com</a></p>
    
</div> 
</div>
<div id="toolbox" class="tooltip box">
    
<href="#" onclick="uploadcreate($('#uploadbox'));">添加一个新上传控件</a> <href="#" onclick="uploadshowpic($(this));">图片显示关闭</a>
</div>
<div id="uploadbox" class="box">
    
</div>

</body>

</html>

上传功能的页面代码(upload.aspx):
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="upload.aspx.cs" Inherits="upload" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    
<title>上传</title>
    
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
<script type="text/javascript" src="scripts/jquery.js"></script>
    
<script type="text/javascript" src="scripts/interface.js"></script>
    
<style type="text/css">
        *
{ margin:0; padding:0; }
        
    
</style>
    
<script type="text/javascript">
        
        
var uploadSelect = function(el){
            el.fadeOut(
"show");        
            parent.uploading(document.getElementById(
"<%=file1.ClientID %>").value,'<%=itemID %>');
            $(
"#<%=frmUpload.ClientID %>").submit();
        };
         
    
</script>
</head>
<body>
    
<form runat="server" id="frmUpload" method="post" enctype="multipart/form-data">
        
<input type="file" runat="server" id="file1" size="40" onchange="uploadSelect($(this));" />        
    
</form>
</body>
</html>

上传功能的服务端代码(upload.aspx.cs)
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

public partial class upload : System.Web.UI.Page
{
    
string picPath = "";
    
string picServer = "/upload";
    
protected string itemID = "";
    
protected void Page_Load(object sender, EventArgs e)
    {

        
if (Request.QueryString["id"!= null)
        {
            itemID 
= Request.QueryString["id"];
        }
  
        
if (IsPostBack)
        {
            picPath 
= Server.MapPath("\\upload");
            doUpload();
        }
    }

    
protected void doUpload()
    {
        
try
        {
            HttpPostedFile file 
= file1.PostedFile;
            
string strNewPath = GetSaveFilePath() + GetExtension(file.FileName);
            file.SaveAs(picPath
+strNewPath);
            
string urlPath = picServer + strNewPath;
            urlPath 
= urlPath.Replace("\\""/");
            WriteJs(
"parent.uploadsuccess('" + urlPath + "','" + itemID + "'); ");
            
        }
        
catch (Exception ex)
        {
            WriteJs(
"parent.uploaderror();");            
        }
    }

    
private string GetExtension(string fileName)
    {
        
try
        {
            
int startPos = fileName.LastIndexOf(".");
            
string ext = fileName.Substring(startPos, fileName.Length - startPos);
            
return ext;
        }
        
catch (Exception ex)
        {
            WriteJs(
"parent.uploaderror('" + itemID + "');");
            
return string.Empty;
        }
    }

    
private string GetSaveFilePath()
    {
        
try
        {
            DateTime dateTime 
= DateTime.Now;
            
string yearStr = dateTime.Year.ToString(); ;
            
string monthStr = dateTime.Month.ToString();
            
string dayStr = dateTime.Day.ToString();
            
string hourStr = dateTime.Hour.ToString();
            
string minuteStr = dateTime.Minute.ToString();
            
string dir = dateTime.ToString(@"\\yyyyMMdd");
            
if (!Directory.Exists(picPath + dir))
            {
                Directory.CreateDirectory(picPath 
+ dir);
            }
            
return dir + dateTime.ToString("\\\\yyyyMMddhhmmssffff");
        }
        
catch (Exception ex)
        {
            WriteJs(
"parent.uploaderror();");
            
return string.Empty;
        }
    }

    
protected void WriteJs(string jsContent)
    {        
        
this.Page.RegisterStartupScript("writejs","<script type='text/javascript'>"+ jsContent+"</script>");
    }

}


基本上就是这些,重点请看第一部份的代码,主要是JS控件显示,还有一个重点是upload.aspx调用父级页面的方法这些实现。

Javascript无刷新上传演示地址:http://www.wathon.com/opensource/js/ajaxuploadv1/upload.html
源代码下载地址:http://www.wathon.com/opensource/js/ajaxuploadv1/ajaxupload_src.zip
无刷新上传在编辑框中的应用演示:http://files.cnblogs.com/huacn/ajaxupload_example.zip

posted on 2007-07-16 00:19 李华顺 阅读(7409) 评论(86)  编辑 收藏 所属分类: Javascript & Ajax.NET

  回复  引用    
2007-07-16 00:33 | host [未注册用户]
welcome
  回复  引用    
2007-07-16 06:00 | 谢小漫 [未注册用户]
only for ie??
  回复  引用    
2007-07-16 06:14 | 谢小漫 [未注册用户]
fuck good
it can work in firefox 2.
thx
  回复  引用  查看    
2007-07-16 07:19 | 布尔      
试一下添加一个文件时,用户点击浏览后,自动调用uploadcreate,这样用户就不用再点一次了,看看这样行不行,我以前实验的时候不行
  回复  引用  查看    
2007-07-16 09:25 | 李华顺      
@布尔
我这个是做一个添加的演示,具体怎么发挥就看需要了

@谢小漫
这个是完全兼容Firefox和IE6的,IE7没有测试过,Firefox下面有动态效果
  回复  引用    
2007-07-16 09:25 | Mekk [未注册用户]
下载你的代码学习学习。
我现在使用微软的AJAX 1.0,不希望又加入其他AJAX类库,但是应该还是可以从你的代码学到不少东西吧。
使用AJAX1.0类库在客户端进行编程的教程似乎比较少,官方的又是英文,并且比较简单。
  回复  引用    
2007-07-16 09:42 | ygl127 [未注册用户]
怎么上传不了
  回复  引用    
2007-07-16 09:53 | 土人 [未注册用户]
不错,好东西
  回复  引用  查看    
2007-07-16 10:58 | zoti      
呵呵 ,不錯。謝謝了。
  回复  引用    
2007-07-16 11:11 | fantasisita [未注册用户]
谢谢楼主,不错
  回复  引用  查看    
2007-07-16 12:56 | GOFI XIAO      
good,3ks
  回复  引用    
2007-07-16 13:43 | moye [未注册用户]
陈芝麻了
  回复  引用    
2007-07-16 13:45 | moye [未注册用户]
用那个Slick HttpUploadModule
还能实现 实时进度显示
基于上传ID号即可
一个SERVER端页面查询当前接管模块对应ID的进度
客户端AJAX与其交互
很简单的东西,不过多了个AJAX~
  回复  引用    
2007-07-16 14:05 | lost [未注册用户]
何必贴这么多代码,看着就乱
  回复  引用  查看    
2007-07-16 17:25 | 杨其仲      
脚本里加这么多 "$" 是什么意思??
  回复  引用    
2007-07-16 20:55 | 西狐 [未注册用户]
非常好,谢谢.
  回复  引用  查看    
2007-07-16 23:03 | 李华顺      
@杨其仲
$是Jquery提供的一个方法,跟 document.getElementById一类似,不过Jquery给这个获取到的对像加了一些实用的方法
  回复  引用  查看    
2007-07-16 23:05 | 李华顺      
@moye
Slick 的是收费的吧,其实我这个主要是实现方法,多会一种方法也不错呀
  回复  引用    
2007-07-17 10:37 | wgmhx [未注册用户]
下载不了。能发一份吗?多谢!wgmhx@hotmail.com
  回复  引用    
2007-07-17 11:58 | 1 [未注册用户]
美工不错
  回复  引用    
2007-07-17 11:59 | 1 [未注册用户]
HOHO
  回复  引用    
2007-07-17 12:49 | woo [未注册用户]
@wgmhx
能下载呀
  回复  引用  查看    
2007-07-17 13:39 | 老夫子系      
前段时间,我也做了一个相似的控件,后来发现有些Bug不知道怎么解决.那个控件也就废弃了. 现在遇到了这个控件,让我眼睛一亮.太感谢李华顺.
  回复  引用  查看    
2007-07-18 16:36 | 李华顺      
@老夫子系
呵呵,不客气
  回复  引用  查看    
2007-07-19 09:24 | Compagnia Te      
先看一下。
  回复  引用    
2007-07-19 17:01 | 浪子 [未注册用户]
我怎么获取路径写进数据库啊,小弟刚刚。希望解答一下谢谢!!!
  回复  引用  查看    
2007-07-19 23:57 | 李华顺      
在 doUpload 这个方法里面 把 strNewPath 这个保存到数据库就可以了嘛
  回复  引用    
2007-07-20 16:48 | 浪子 [未注册用户]
还是没搞定。我做了的是个产品系统,还有很多字段的,不知道,怎么取到图片的路径,给我例子行吗?谢谢!!
  回复  引用  查看    
2007-07-20 21:12 | 李华顺      
@浪子
图片路径就是在 strNewPath 这里面的嘛
怎么存就是别的事情了呀!
就在上传的时候存就可以了,你是不是以为要返回的时候存呀。
存到数据库的方法请写到
protected void doUpload()
这个方法里面,写在
WriteJs("parent.uploadsuccess('" + urlPath + "','" + itemID + "'); ");
这句的前面,最好是开线程来存放。
如 doSaveToDatteBase(其它的内容,strNewPath)
  回复  引用    
2007-07-25 19:40 | 育 [未注册用户]
太笨了,看不懂
  回复  引用    
2007-07-29 23:09 | Kenny [未注册用户]
不能下载,请发我一份谢谢!

Kenny_tian(at)tom.com
  回复  引用    
2007-07-30 15:08 | greki [未注册用户]
<input type="file" runat="server" id="file1" size="40" onchange="uploadSelect($(this));" />


有些问题,如果手段任意输入,就会显示图片上传
  回复  引用    
2007-07-30 15:37 | greki [未注册用户]
onchange 函数里最好加 图片有效性判断。。。不才,只想说下自己想法,写得不好不要见怪

<head runat="server">
<title>无标题页</title>
<style >
img{
width:0px;
}

</style>
<script language ="javascript" type="text/javascript" >
var onError=false;
function Upload(ojb){
document .getElementById ('img').src=ojb.value;
if(!onError){
document.form1.submit ();
}
}

function ImageError(){
onError=true;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="upd" runat="server" onchange="Upload(this)" />
<img id="img" onerror ="ImageError()" />
</div>
</form>
</body>
</html>
  回复  引用  查看    
2007-07-30 16:36 | 李华顺      
@greki
恩,不错
  回复  引用    
2007-07-30 19:34 | 天盖川 [未注册用户]
我把代码复制下来运行,好像有错。。
是在html文件的
最后 添加一个新上传控件 onclick="uploadcreate($('#uploadbox'));">
这里。。


  回复  引用    
2007-07-30 19:36 | 天盖川 [未注册用户]

不好意思,能给我一份源码么,我用这上面的代码跑不出效果来。。
我的邮箱是 faweeky@gmail.com

谢谢了。。
  回复  引用  查看    
2007-07-30 20:06 | 李华顺      
@天盖川
晕!!!!!
我服了你了,看东西都不仔细,没看到后面有打包的源代码下载连接吗?