ajax 无刷新上传

最近要做微信的图文上传,因为一个图文了表中可以有多个图文,所有按钮需要随时添加,所以做了一种无刷新上传的方法。

首先我们要在html页面中写上这样的几段代码

javascript:

 $(function () {
        //这个是为了绑定我们所有的上传按钮,包括动态添加的按钮
            $(document).on("change", ".filebutton", function () {
                $(this).parent().children("span").html(‘开始上传中....‘);
                $(this).parent().submit();
            });
        })
    //这个方法是为了让iframe中的页面调用修改本页内容的方法(可以根据自己需要修改)
        function uploadSuccess(msg) {
            var info = msg.split(‘|‘);
            var _from = $("#" + info[2] + "_ts");
            _from.html(info[0]);
            if (info[1] != "") {
                _from.append("<a href=‘uplod/" + info[1] + "‘ target=\"_blank\" imgurl=\"" + info[1] + "\">查看图片</a>");
            }
            else {
                _from.append("<a imgurl=\"\"></a>");
            }
        }

html

 <form method="post" action="../ajax/Upload.ashx?id=boximg" target=‘boximg_f‘  enctype="multipart/form-data"><!--这里用到了target属性来指向下面的iframe让页面在iframe中刷新-->
       <input class="filebutton" type="file" id="boximg" name="fileUp" />
       <span id="boximg_ts" runat="server" class="help-inline">上传的文件不能大于500KB</span> </form>

<!--这里隐藏这个iframe让别人看不出来刷新的效果-->
 <iframe id="boximg_f" name="boximg_f" style="display:none;"></iframe>

然后我们需要建立这个Upload.ashx文件来接收post过来的文件数据

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Net;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using WeiXinHaiBLL;

namespace WeiXinHai.ajax
{
    /// <summary>
    /// Upload 的摘要说明
    /// </summary>
    public class Upload : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //string fname = context.Request.QueryString["op"].ToString();
            //string str =fname+"({name:‘judy‘,age:‘23‘})";

            string id = context.Request.QueryString["id"];
            try
            {
                //获取当前Post过来的file集合对象,在这里我只获取了<input type=‘file‘ name=‘fileUp‘/>的文件控件
                string file1 = "";
                if (id == "citu")
                {
                    file1 = "fileUps";
                }
                else
                { file1 = "fileUp"; }
                HttpPostedFile file = context.Request.Files[file1];
                if (file != null)
                {
                    //当前文件后缀名
                    string ext = Path.GetExtension(file.FileName).ToLower();
                    //验证文件类型是否正确
                    if (!ext.Equals(".gif") && !ext.Equals(".jpg") && !ext.Equals(".png") && !ext.Equals(".bmp"))
                    {
                        //ajax/uplodereturn.html
                        //这里window.parent.uploadSuccess()是我在前端页面中写好的javascript function,此方法主要用于输出异常和上传成功后的图片地址
                        context.Response.Redirect("uplodereturn.html?error=fileerror&id=" + id, false);
                        return;
                    }
                    //验证文件的大小
                    if (file.ContentLength > (1024 * 500))
                    {
                        //这里window.parent.uploadSuccess()是我在前端页面中写好的javascript function,此方法主要用于输出异常和上传成功后的图片地址
                        context.Response.Redirect("uplodereturn.html?error=tobig&id=" + id, false);
                        return;
                    }
                    FileInfo files = new FileInfo(file.FileName);

                    //当前文件上传的目录
                    string serverPath = System.Web.HttpContext.Current.Server.MapPath("~");
                    string selfPath = "images\\uplod\\";

                    //当前待上传的服务端路径
                    string toFilePath = Path.Combine(serverPath, selfPath);
                    //生成将要保存的随机文件名
                    string fileName = GetImageName() + ext;
                    //获得要保存的文件路径
                    string serverFileName = toFilePath + fileName;

                    //物理完整路径
                    string toFileFullPath = serverFileName; //HttpContext.Current.Server.MapPath(toFilePath);

                    //将要保存的完整文件名
                    string toFile = toFileFullPath;//+ fileName;

                    context.Request.Files[0].SaveAs(toFile);

                    //开始上传
                    //file.SaveAs(imageUrl);
                    //这里window.parent.uploadSuccess()是我在前端页面中写好的javascript function,此方法主要用于输出异常和上传成功后的图片地址
                    //如果成功返回的数据是需要返回两个字符串,我在这里使用了|分隔  例: 成功信息|/Test/hello.jpg
                    context.Response.Redirect("uplodereturn.html?type=" + fileName + "&id=" + id, false);
                    return;
                }
                else
                {
                    //上传失败
                    context.Response.Redirect("uplodereturn.html?r=a&id=" + id, false);
                    return;
                }
            }
            catch (Exception ex)
            {
                //上传失败
                context.Response.Redirect("uplodereturn.html?r=a&id=" + id, false);
                return;
            }
            //context.Response.Write("hello word")
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        #region Private Methods
        /// <summary>
        /// 检查是否为合法的上传图片
        /// </summary>
        /// <param name="_fileExt"></param>
        /// <returns></returns>
        private bool CheckImageExt(string _ImageExt)
        {
            string[] allowExt = new string[] { ".jpg", ".png", ".bmp", ".gif", ".pdf", ".jpeg", };
            for (int i = 0; i < allowExt.Length; i++)
            {
                if (allowExt[i] == _ImageExt) { return true; }
            }
            return false;

        }

        private string GetImageName()
        {
            Random rd = new Random();
            StringBuilder serial = new StringBuilder();
            serial.Append(DateTime.Now.ToString("yyyyMMddHHmmssff"));
            serial.Append(rd.Next(0, 999999).ToString());
            return serial.ToString();

        }

        #endregion
    }
}

剩下的我们就要新建一个用来调用ifarme父级uploadSuccess方法的页面uplodereturn.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></title>
    <script>
        var url = window.location.search;
        if (url.indexOf("?") != -1) {
            var strurl = url.substr(1)
            strs = strurl.split("&");
            var returntype = ‘‘;
            if ([strs[0].split("=")[0]] == ‘type‘) {
                returntype = "上传成功|" + unescape(strs[0].split("=")[1]);
                //window.parent.uploadSuccess("上传成功|" + unescape(strs[0].split("=")[1]));
            }
            else if ([strs[0].split("=")[0]] == ‘error‘) {
                returntype = (unescape(strs[0].split("=")[1]) == "fileerror" ? "文件格式错误" : "上传文件过大,请重新上传!") + "|";
                //window.parent.uploadSuccess(unescape(strs[0].split("=")[1]));
            }
            if (strs[1].split("=")[0] == ‘id‘) {
                returntype += "|" + unescape(strs[1].split("=")[1]);
            }
            window.parent.uploadSuccess(returntype);
        }
    </script>
</head>
<body>
</body>
</html>

然后大功告成,我们添加的时候需要添加上最上面的html代码中的form部分就可以了

这里的原理是用from 的target 来让这个from的刷新过程在iframe中进行,这样的话我们隐藏掉iframe的时候就看不出页面的刷新效果

同时我们又在这个新建的html中拼写好我们想要的参数调用父级写好的方法,然后达到更改页面的效果。

这里我的方法是修改了span部分的内容。

时间: 2024-07-28 20:35:20

ajax 无刷新上传的相关文章

移动端图片上传解决方案localResizeIMG先压缩后ajax无刷新上传

现在科技太发达,移动设备像素越来越高,随便一张照片2M+,但是要做移动端图片上传和pc上略有不同,移动端你不能去限制图片大小,让用户先处理图片再上传,这样不现实.所以理解的解决方案就是在上传先进行图片压缩,然后再把压缩后的图片上传到服务器. 一翻google之后,发现了localResizeIMG,它会对图片进行压缩成你指定宽度及质量度并转换成base64图片格式,那么我们就可以把这个base64通过ajax传到后台,再进行保存,先压缩后上传的目的就达到了. 处理过程 LocalResizeIM

ajaxfileupload.js插件结合一般处理文件实现Ajax无刷新上传

先上几张图更直观展示一下要实现的功能.本功能主要通过Jquery ajaxfileupload.js插件结合ajaxUpFile.ashx一般应用程序处理文件实现Ajax无刷新上传功能,结合NPOI2.0实现数据读取.这个功能在实际工作种经经常使用到,希望能给须要做这方面的人有些帮助. 一.功能页面布局及介绍 1.上传页面布局及input file上传功能 2.上传页面文件正在上传效果 3.上传完毕效果,多文件展示区 二.功能代码实现及资源引用 1.js资源文件引用 html页面js引用.须要引

动端图片上传解决方案localResizeIMG先压缩后ajax无刷新上传

现在科技太发达,移动设备像素越来越高,随便一张照片2M+,但是要做移动端图片上传和pc上略有不同,移动端你不能去限制图片大小,让用户先处理图片再上传,这样不现实.所以理解的解决方案就是在上传先进行图片压缩,然后再把压缩后的图片上传到服务器. 一翻google之后,发现了localResizeIMG,它会对图片进行压缩成你指定宽度及质量度并转换成base64图片格式,那么我们就可以把这个base64通过ajax传到后台,再进行保存,先压缩后上传的目的就达到了. 处理过程 LocalResizeIM

Ajax 无刷新上传文件插件 uploadify 的使用

在表单中无法直接使用 Ajax 上传文件,解决的思路可以是使用插件无刷新地上传文件,返回文件上传后的地址,然后把该地址作为 Ajax 的参数传递给服务器端进行数据库处理.可以使用 uploadify 插件来实现该思路. 官方网站:http://www.uploadify.com 文档地址:http://www.uploadify.com/documentation/ 插件有 Flash 版 和 HTML5 版,项目中用到的是 Flash 版. 下载 Demo 并解压: 其中 index.php

jquery 的ajax无刷新上传文件之后,页面还是会莫名的刷新-----解决办法

文件上传用到全局数组: $_FILES 只需要把下面的 <button onclick="post()">提交</button> 改为 <input type="button" onclick="post()" value="提交"/>就不会刷新页面了!!! 参考 http://bbs.csdn.net/topics/391852021 what fuck ... sb html   我在那

jQuery.form Ajax无刷新上传错误 (jQuery.handleError is not a function) 解决方案

今天,随着ajaxfileupload时间firebug财报显示,"jQuery.handleError is not a function"错误.因为一旦使用jQuery.form问题,我对照曾经的项目才发现,在这个项目中使用的jQuery是1.10.2的版本号,而曾经是使用的1.4.2.度娘一番之后,找到解决的方法:jQuery.handleError is not a function 报错原因是: handlerError仅仅在jquery-1.4.2之前的版本号中存在.jqu

jQuery.form Ajax无刷新上传报错 (jQuery.handleError is not a function) 解决办法

今天在用ajaxfileupload时firebug报了一个"jQuery.handleError is not a function"的错误.因为在以前使用jQuery.form一直都没有出现过这个问题,我对比以前的项目才发现,在这个项目中使用的jQuery是1.10.2的版本,而以前是使用的1.4.2.度娘一番之后,找到解决办法:jQuery.handleError is not a function 报错原因是: handlerError只在jquery-1.4.2之前的版本中存

jQuery无刷新上传之uploadify简单试用

先简单的侃两句:貌似已经有两个月的时间没有写过文章了,不过仍会像以前那样每天至少有一至两个小时是泡在园子里看各位大神的文章.前些天在研究"ajax无刷新上传"方面的一些插件,用SWFUpload实现了无刷新上传的功能,不过个人觉得不是很完美. 昨天在网上找到了一个叫做uploadify的jquery上传插件,看到园子里有几篇文章也是介绍这个插件的,心想何不用这个试试. 不过园子里的这几篇文章用到的uploadify还是以前的旧版本uploadify-v2.1.0,我在官网上下载的是up

jQuery AJAX 网页无刷新上传示例

新年礼,提供简单.易套用的 jQuery AJAX 上传示例及代码下载.后台对文件的上传及检查,以 C#/.NET Handler 处理 (可视需要改写成 Java 或 PHP). 有时做一个网站项目 (不论是否 ASP.NET),内附的 FileUpload 控件,功能不足 (页面必须刷新.不支援 AJAX),或外观太丑被用户嫌弃 (却无法透过 CSS 自定义外观).网路上虽已有许多可用的示例,如: jQuery File Upload,但功能太强大.外观复杂,欲仅取出部分功能来引用,反而不易