ajax上传图片 jquery插件 jquery.form.js 的方法 ajaxSubmit; AjaxForm与AjaxSubmit的差异

先引入脚本  这里最好是把jquery的脚本升级到1.7

<script src="js/jquery-1.7.js" type="text/javascript"></script>
    <script src="js/jquery.form.js" type="text/javascript"></script>

 

$("#btnUpload").click(function () {
               $("#mytype").val("updateuserinfo");
               alert("开始上传喽");
               $("#form1").ajaxSubmit({

                   dataType: 'json',
                   success: function (data) {
                       alert("上传成功");
                   },
                   error: function (xhr) {
                       alert("上传失败");
                   }
               });
           });

 

<form id="form1" action="handler/xxHandler.ashx" method="post" enctype="multipart/form-data">
        <table>
            <tr>
                <td>附件:</td>
                <td>
                    <input type="file" name="fileName" />
                    <input type="hidden" name="uid" />
                    </td>
            </tr>
            <tr>
                <td>:</td>
                <td>
                   <input type="button" id="btnUpload" value="点击上传"/> <input type="text" name="type" id="mytype"  /></td>
            </tr>
             
        </table>
 
    </form>

后台保存图片代码

public static string DoUpFile(HttpContext context, string id, int type)
        {
            bool isUpload = false;
            string returnFile = "";
            if (context.Request.Files.Count > 0)
            {
                HttpPostedFile file = context.Request.Files[0];
                string fileNameExt = file.FileName.Substring(file.FileName.LastIndexOf("."));
                if (fileNameExt.ToLower() != ".jpg" && fileNameExt.ToLower() != ".mp3" &&
                    fileNameExt.ToLower() != ".png" && fileNameExt.ToLower() != ".jpeg")
                {
                    //throw new Exception("文件格式错误,不能识别。");
                    throw new MessageJxtException(Message.文件格式错误上传失败);
                }

                string yearMonthDay = DateTime.Now.ToString("yyyMMdd");
                string filePath = "";

                string name = DateTime.Now.ToString("yyyyMMdd_HHmmssffff");
                switch (type)
                {
                    case 1: //头像
                        filePath = context.Server.MapPath(string.Format("data/{0}", type));
                        name = id;
                        break;
                    case 3: //通知图片
                    case 4: //聊天图片
                    case 5: //通知声音
                    case 6: //聊天声音
                        filePath = context.Server.MapPath(string.Format("data/{0}/{1}", type, yearMonthDay));
                        break;
                    default:
                        filePath = context.Server.MapPath(string.Format("data/{0}/{1}", type, yearMonthDay));
                        break;
                }

                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }
                string myFileName = name + fileNameExt.ToLower();
                string savePath = filePath + "\" + myFileName;

                file.SaveAs(savePath);
                //如果是图片,生成缩略图
                if (fileNameExt.ToLower() == ".jpg" || fileNameExt.ToLower() == ".png" ||
                    fileNameExt.ToLower() == ".jpeg")
                {
                    //缩略图地址
                    string thumbnailName = filePath + "\" + name + "_s" + fileNameExt.ToLower();
                    Thumbnail.CutForSquare(savePath, thumbnailName, 200, 70);
                }
                isUpload = true;
                returnFile = myFileName;

            }

}


保存缩略图(正方形裁剪)

/// <summary>  
        /// 正方型裁剪  
        /// 以图片中心为轴心,截取正方型,然后等比缩放  
        /// 用于头像处理  
        /// </summary>  
        /// <param name="postedFile">原图HttpPostedFile对象</param>  
        /// <param name="fileSaveUrl">缩略图存放地址</param>  
        /// <param name="side">指定的边长(正方型)</param>  
        /// <param name="quality">质量(范围0-100)</param>  
        public static void CutForSquare(System.IO.Stream fromFile, string fileSaveUrl, int side, int quality)
        {
            //创建目录  
            string dir = Path.GetDirectoryName(fileSaveUrl);
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);

            //原始图片(获取原始图片创建对象,并使用流中嵌入的颜色管理信息)  
            System.Drawing.Image initImage = System.Drawing.Image.FromStream(fromFile, true);

            //原图宽高均小于模版,不作处理,直接保存  
            if (initImage.Width <= side && initImage.Height <= side)
            {
                initImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            else
            {
                //原始图片的宽、高  
                int initWidth = initImage.Width;
                int initHeight = initImage.Height;

                //非正方型先裁剪为正方型  
                if (initWidth != initHeight)
                {
                    //截图对象  
                    System.Drawing.Image pickedImage = null;
                    System.Drawing.Graphics pickedG = null;

                    //宽大于高的横图  
                    if (initWidth > initHeight)
                    {
                        //对象实例化  
                        pickedImage = new System.Drawing.Bitmap(initHeight, initHeight);
                        pickedG = System.Drawing.Graphics.FromImage(pickedImage);
                        //设置质量  
                        pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        //定位  
                        Rectangle fromR = new Rectangle((initWidth - initHeight) / 2, 0, initHeight, initHeight);
                        Rectangle toR = new Rectangle(0, 0, initHeight, initHeight);
                        //画图  
                        pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel);
                        //重置宽  
                        initWidth = initHeight;
                    }
                    //高大于宽的竖图  
                    else
                    {
                        //对象实例化  
                        pickedImage = new System.Drawing.Bitmap(initWidth, initWidth);
                        pickedG = System.Drawing.Graphics.FromImage(pickedImage);
                        //设置质量  
                        pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        //定位  
                        Rectangle fromR = new Rectangle(0, (initHeight - initWidth) / 2, initWidth, initWidth);
                        Rectangle toR = new Rectangle(0, 0, initWidth, initWidth);
                        //画图  
                        pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel);
                        //重置高  
                        initHeight = initWidth;
                    }

                    //将截图对象赋给原图  
                    initImage = (System.Drawing.Image)pickedImage.Clone();
                    //释放截图资源  
                    pickedG.Dispose();
                    pickedImage.Dispose();
                }

                //缩略图对象  
                System.Drawing.Image resultImage = new System.Drawing.Bitmap(side, side);
                System.Drawing.Graphics resultG = System.Drawing.Graphics.FromImage(resultImage);
                //设置质量  
                resultG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                resultG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                //用指定背景色清空画布  
                resultG.Clear(Color.White);
                //绘制缩略图  
                resultG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, side, side), new System.Drawing.Rectangle(0, 0, initWidth, initHeight), System.Drawing.GraphicsUnit.Pixel);

                //关键质量控制  
                //获取系统编码类型数组,包含了jpeg,bmp,png,gif,tiff  
                ImageCodecInfo[] icis = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo ici = null;
                foreach (ImageCodecInfo i in icis)
                {
                    if (i.MimeType == "image/jpeg" || i.MimeType == "image/bmp" || i.MimeType == "image/png" || i.MimeType == "image/gif")
                    {
                        ici = i;
                    }
                }
                EncoderParameters ep = new EncoderParameters(1);
                ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality);

                //保存缩略图  
                resultImage.Save(fileSaveUrl, ici, ep);

                //释放关键质量控制所用资源  
                ep.Dispose();

                //释放缩略图资源  
                resultG.Dispose();
                resultImage.Dispose();

                //释放原始图片资源  
                initImage.Dispose();
            }
        }


比较完整的参考资料(上传图片,删除图片,带上传进度条显示

http://www.cnblogs.com/cysolo/archive/2013/06/09/3129119.html


最后,我们说一下 AjaxForm与AjaxSubmit的差异

AjaxForm 是用来对表单进行验证,例如提交一个用户名过去看看是否符合规定等等

AjaxSubmit 则是将整个表单都用ajax的方式进行了提交,包括图片都可以提交过去。

原文地址:https://www.cnblogs.com/joeylee/p/3472466.html