异步加载不刷新input type=file上传照片

(1)引用jQuery:jquery-1.8.0.js(可以是别的jQuery)

(2)引用jQuery:jquery.form.js

(3)页面代码

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="JqueryFormTest.aspx.cs" Inherits="JqueryFormTest" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <%--先引用jQuery-1.8,再引用jQuery.form.js--%>
    <script src="jquery1.8/jquery-1.8.0.js"></script>
    <script src="jquery.form.js"></script>
</head>
<body>
    <form id="form1" runat="server" method="post"><%--此处必须填method="post"--%>
    <!--method="post"不能省略,在ie里面必不可少-->
    <input type="file" id="file_upload" name="file_upload" value="" /><%--name给服务器接收的--%>
    <br />
    <input type="button" id="topimg_btn" value="上传" />
    </form>
</body>
</html>
<script>
    //上传按钮的点击事件
    $("#topimg_btn").click(function () {
        $("#form1").ajaxSubmit({
            url: "ajax/img.ashx",//ajax是个文件夹
            type: "post",
            success: function (data) {
                alert(data);
                //IE显示图片会默认加上<PRE></PRE>,着必须要把去除掉才能在低版本ie显示  
                data = data.replace("<PRE>", "").replace("</PRE>", "");

                //清空file控件里面的值  
                var file = $("#file_upload");
                file.after(file.clone().val(""));
                file.remove();
            }
        });
    });
</script>

(4)img.ashx的代码

<%@ WebHandler Language="C#" Class="img" %>

using System;
using System.Web;

public class img : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        //获取上传的文件的对象  
        HttpPostedFile img = context.Request.Files["file_upload"];

        //获取上传文件的名称  
        string s = img.FileName;
        //截取获得上传文件的名称(ie上传会把绝对路径也连带上,这里只得到文件的名称)  
        string str =DateTime.Now.ToString("yyyyMMddhhmmss")+s.Substring(s.LastIndexOf("\") + 1);
        string path = "~/images/" + str;//images是文件夹
        //保存文件  s
        img.SaveAs(context.Server.MapPath(path));
        //HttpRuntime.AppDomainAppVirtualPath主要是获取应用程序虚拟路径名称,因为响应给页面时不会自动添加而导致无法显示图片
        context.Response.Write(HttpRuntime.AppDomainAppVirtualPath + path.Substring(1));//path.Substring(1)用来去除第一个~字符
        
        
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

完!!!

原文地址:https://www.cnblogs.com/wwz-wwz/p/6276970.html