1、利用FormData实现文件上传

<input type="file" id="avatar" name="avatar">
<button type="button">保存</button>
('button').click(function(){
 var files = $('#avatar').prop('files'); //多个
 //或者
 var files = $('#avatar')[0].files[0] //单个
 
 var data = new FormData();
 data.append('avatar', files[0]);
 
 $.ajax({
  url: '/api/upload',
  type: 'POST',
  data: data,
  cache: false,
  processData: false,
  contentType: false
 });
});

2、一般处理程序上传文件

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
using Newtonsoft.Json;

namespace CCOA.App.common.api
{
    /// <summary>
    /// CommUploadFile 的摘要说明
    /// </summary>
    public class CommUploadFile : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            try {
            HttpPostedFile file = context.Request.Files["file1"];
            //是否上传文件
            if (file.ContentLength <= 0) //文件大小
            {
                //请选择要上传的文件
                context.Response.Write("");
                return;
            }

            //上传文件大小检测
            if (file.ContentLength > 1024 * 1024*5)
            {
                //上传文件大小不能超过5M
                context.Response.Write("");
                return;
            }

            //上传文件后缀名检测
            string filename = file.FileName; //文件绝对地址
            string suffix = Path.GetExtension(filename); //截取后缀
            //if (suffix != ".jpg" & suffix != ".jpeg")
            //{
            //    context.Response.Write("只允许上传jpg文件");
            //    return;
            //}

            #region 保存文件
            //重命名:GUID(全球唯一标识符)推荐!!!
            filename = string.Format("{0}{1}", Guid.NewGuid().ToString("N"), suffix);

            //创建目录
            string dirFullPath = context.Server.MapPath("~/UploadFile/");

            //如果文件夹不存在,则先创建文件夹
            if (!Directory.Exists(dirFullPath))
            {
                Directory.CreateDirectory(dirFullPath);
            }

            //将两个字符组合成一个路径
            string fileFullPath = Path.Combine(dirFullPath, filename);
            //保存文件
            file.SaveAs(fileFullPath);

            string clientFilePath = "/CCOA/UploadFile/" + filename;
            context.Response.Write(clientFilePath);
            }
            catch (Exception ex)
            {
                context.Response.Write("");
            }
            #endregion
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}