asp.net中利用jQuery Form插件上传文件

jQuery Form Plugin:http://pan.baidu.com/s/1jG81W3O

jquery-1.8.3.min.js:http://pan.baidu.com/s/1i3l3zCD

<!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 src="Scripts/jquery-1.8.3.min.js" type="text/javascript"></script>
    <script src="Scripts/MyAjaxForm.js" type="text/javascript"></script>
    <script type="text/javascript">

        $(function () {
            $("#btn").click(function () {
                $("#fm1").ajaxSubmit({
                    url: "img.ashx",
                    type: "post",
                    success: function (data) {
                        //IE显示图片会默认加上<PRE></PRE>,着必须要把去除掉才能在低版本ie显示
                        data = data.replace("<PRE>", "").replace("</PRE>", "");
                        $("#divimg").append("<img src='" + data + "' width='200px' height='200px'/>");
                        //清空file控件里面的值
                        var file = $("#btnfile");
                        file.after(file.clone().val(""));
                        file.remove();
                    }
                });
            });
        })
    </script>
</head>
<body>
  <form id="fm1" method="post"><!--method="post"不能省略,在ie里面必不可少-->
    <input type="file" id="btnfile" name="btnfile" value="提交"/>
    <br />
    <input type="button" id="btn" value="上传"/>
  </form>
  <div id="divimg"></div>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication2
{
    /// <summary>
    /// img 的摘要说明
    /// </summary>
    public class img : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //获取上传的文件的对象
            HttpPostedFile img = context.Request.Files["btnfile"];

            //获取上传文件的名称
            string s = img.FileName;
            //截取获得上传文件的名称(ie上传会把绝对路径也连带上,这里只得到文件的名称)
            string str = s.Substring(s.LastIndexOf("\\") + 1);
            //给文件添加随机戳
            string path = "/Upload/" + Guid.NewGuid() + str;
            //保存文件
            img.SaveAs(context.Server.MapPath(path));
            context.Response.Write(path);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
当然,我们也可以在input[type=file]的cange事件中处理,$("#btnfile").change(.......


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值