文件上传之伪Ajax方式上传 (转)

http://www.cnblogs.com/keke/archive/2011/05/09/2041370.html

  最近做项目遇到了些关于上传的功能模块,在网上找了很多关于上传的相关资料,找到了一个依赖于Jquery写的jquery.uploadify类库,这个类库的上传功能支持的非常全面,不过遗憾的是它是依赖于flash来处理上传,所以在页面中呈现不了传统的上传控件的浏览方式,因为项目需求必须以传统的<input type='file'/>形态模式出现在页面中!所以只好舍去jquery.uploadify类库强大功能,于是乎自己研究了一番。最终实现了一个静态上传的功能!好了,废话不多说,代码献上!如阁下有更好的建议欢迎强力拍砖!小弟不胜感激!

首先我的后台程序用的是ASP.NET

Javascript用到了Jquery类库

这里先给大家介绍下为什么叫伪Ajax方式上传,因为这个上传不会使当前页面产生刷新的效果,并且也没有用任何的Ajax技术,但是实现了页面无刷新的上传效果,因此小弟称为伪Ajax方式。呵呵,关子卖了很久了!介绍下这个核心吧!核心主要是利用<form>和<iframe>实现!相信对Web 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>File Upload</title>
</head>
<body>
    <!--
        大家注意到这个form的target的了么?这个target属性的值frameFile,是form之后的iframe的name值,
        这样的写法是让当前的form表单在提交表单内容的时候转交给iframe中进行页面中表单处理,
        并且不会产生当前页面跳转!
     -->
    <form id='formFile' name='formFile' method="post" action='/uploads.aspx' target='frameFile' enctype="multipart/form-data">
        <input type='file' id='fileUp' name='fileUp' />
        <div id='uploadLog'></div>
        <br />
        <img width='200' src='' height='200' id='imgShow' alt='缩略图' />        
    </form>

    <!--
        这个iframe拿到post过来的表单数据后会开始在自身内部访问post过来的页面地址,在内部中它会刷新页面,
        但是这已不重要了,因为当前的iframe已经被我display:none隐藏了!所以这样给用户看起来像是无刷新的
        页面文件上传,其实只是做一个一个小小的技巧!
    -->
    <iframe id='frameFile' name='frameFile' style=' display:none;'></iframe>
</body>
</html>

后台:

<script type="text/javascript" language="javascript">
        $(function () {
            $('#fileUp').change(function () {
                $('#uploadLog').html('开始上传中....');
                $('#formFile').submit();
            });
        })
        function uploadSuccess(msg) {
            if (msg.split('|').length > 1) {
                $('#imgShow').attr('src', msg.split('|')[1]);
                $('#uploadLog').html(msg.split('|')[0]);
            } else {
                $('#uploadLog').html(msg);
            }
        }
</script>


/// <summary>
/// 页面加载.在这里我简单的写了下文件上传的处理Code
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        //获取当前Post过来的file集合对象,在这里我只获取了<input type='file' name='fileUp'/>的文件控件
        HttpPostedFile file = Request.Files["fileUp"];
        if (file != null)
        {
            //当前文件上传的目录
            string path = Server.MapPath("~/Test/");
            //当前待上传的服务端路径
            string imageUrl = path + Path.GetFileName(file.FileName);
            //当前文件后缀名
            string ext = Path.GetExtension(file.FileName).ToLower();
            //验证文件类型是否正确
            if (!ext.Equals(".gif") && !ext.Equals(".jpg") && !ext.Equals(".png") && !ext.Equals(".bmp"))
            {
                //这里window.parent.uploadSuccess()是我在前端页面中写好的javascript function,此方法主要用于输出异常和上传成功后的图片地址
                Response.Write("<script>window.parent.uploadSuccess('你上传的文件格式不正确!上传格式有(.gif、.jpg、.png、.bmp)');</script>");
                Response.End();
            }
            //验证文件的大小
            if (file.ContentLength > 1048576)
            {
                //这里window.parent.uploadSuccess()是我在前端页面中写好的javascript function,此方法主要用于输出异常和上传成功后的图片地址
                Response.Write("<script>window.parent.uploadSuccess('你上传的文件不能大于1048576KB!请重新上传!');</script>");
                Response.End();
            }
            //开始上传
            file.SaveAs(imageUrl);

            //这里window.parent.uploadSuccess()是我在前端页面中写好的javascript function,此方法主要用于输出异常和上传成功后的图片地址
            //如果成功返回的数据是需要返回两个字符串,我在这里使用了|分隔  例: 成功信息|/Test/hello.jpg
            Response.Write("<script>window.parent.uploadSuccess('Upload Success!|/Test/" + file.FileName + "');</script>");
            Response.End();
        }
        else
        {
            //上传失败
            Response.Write("upload lose!");
            Response.End();
        }
    }
    catch {
        //上传失败
        Response.Write("upload lose!");
        Response.End();
    }
}

原文地址:https://www.cnblogs.com/blackbean/p/2041394.html