asp.net 中使用JQuery Ajax 上传文件

首先创建一个网页,网页中添加如下代码。

  <h3>Upload File using Jquery AJAX in Asp.net</h3>  
    <table>  
        <tr>  
        <td>File:</td>  
        <td>  
            <asp:FileUpload ID="fupload" runat="server"  onchange=‘prvimg.UpdatePreview(this)‘ /></td>  
        <td><asp:Image ID="imgprv" runat="server" Height="90px" Width="75px"  /></td>  
        </tr>  
        <tr>  
        <td></td>  
        <td><asp:Button ID="btnUpload" runat="server" cssClass="button" Text="Upload Selected File" /></td>  
        </tr>  
    </table>  

接着在添加jquery代码

$("#btnUpload").click(function (evt) {  
            var fileUpload = $("#fupload").get(0);  
            var files = fileUpload.files;  
  
            var data = new FormData();  
            for (var i = 0; i < files.length; i++) {  
                data.append(files[i].name, files[i]);  
            }  
  
            $.ajax({  
                url: "FileUploadHandler.ashx",  
                type: "POST",  
                data: data,  
                contentType: false,  
                processData: false,  
                success: function (result) { alert(result); },  
                error: function (err) {  
                    alert(err.statusText)  
                }  
            });  
  
            evt.preventDefault();  
        });  

FileUploadHandler.ashx中的代码

<%@ WebHandler Language="C#" Class="FileUploadHandler" %>    
     
using System;    
using System.Web;    
     
public class FileUploadHandler : IHttpHandler  
{    
     
    public void ProcessRequest (HttpContext context)  
    {    
        if (context.Request.Files.Count > 0)    
        {    
            HttpFileCollection files = context.Request.Files;    
            for (int i = 0; i < files.Count; i++)    
            {    
                HttpPostedFile file = files[i];    
                string fname = context.Server.MapPath("~/uploads/" + file.FileName);    
                file.SaveAs(fname);    
            }    
            context.Response.ContentType = "text/plain";    
            context.Response.Write("File Uploaded Successfully!");    
        }    
     
    }    
     
    public bool IsReusable  
    {    
        get   
        {    
            return false;    
        }    
    }    
     
}   

最后效果如下:

技术分享

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。