ajax图片上传(asp.net +jquery+ashx)

一、建立Default.aspx页面

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





    ajax图片上传
    
    
    
    


    
网站Logo


二、新建一个一般处理文件Handler.ashx

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

using System;
using System.Web;

public class Handler : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        HttpPostedFile _upfile = context.Request.Files["File1"];
        if (_upfile == null)
        {
            ResponseWriteEnd(context, "4");//请选择要上传的文件
        }
        else
        {
            string fileName = _upfile.FileName;/*获取文件名: C:\Documents and Settings\Administrator\桌面\123.jpg*/
            string suffix = fileName.Substring(fileName.LastIndexOf(".") + 1).ToLower();/*获取后缀名并转为小写: jpg*/
            int bytes = _upfile.ContentLength;//获取文件的字节大小

            if (suffix != "jpg")
                ResponseWriteEnd(context, "2"); //只能上传JPG格式图片
            if (bytes > 1024 * 1024)
                ResponseWriteEnd(context, "3"); //图片不能大于1M

            _upfile.SaveAs(HttpContext.Current.Server.MapPath("~/images/logo.jpg"));//保存图片
            ResponseWriteEnd(context, "1"); //上传成功
        }
    }

    private void ResponseWriteEnd(HttpContext context, string msg)
    {
        context.Response.Write(msg);
        context.Response.End();
    }
    
    public bool IsReusable {
        get {
            return false;
        }
    }
}


 

项目结构图

 

你可能感兴趣的:(jquery,Asp.Net,asp.net,jquery,ajax,function,upload,file)