04
2014
07

Asp.Net中使用ajaxFileUpload进行图片上传

 在开发中,经常会遇到需要上传图片的时候,可以使用已经有的上传插件ajaxFileUpload进行上传,点击某个按钮,将调用uploadImg方法,参数imgfileId是上传的file的input的ID

function uploadImg(imgfileId) {
    $.ajaxFileUpload({
        fileElementId: imgfileId,
        url: 'jqueryUpImg.ashx',
        data: {
            'name': "pro", //存储的文件名
            'width': "500,250,125", //需要切图的大小
            'height': "360,180,90"
        },
        dataType: 'json',
        success: function (data, textStatus) {
            if (textStatus == "success") {
                $("#txtProImg").val(data.img);
                $("#txtProImg_Big").val(data.imgBig);
                $("#txtProImg_Middle").val(data.imgMiddle);
                $("#txtProImg_Small").val(data.imgSmall);
                $(".img_middle").find("img").attr("src", data.imgMiddle);
            }
            else {
                alert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            var msg = XMLHttpRequest.responseText;
            //alert(msg);
            alert(errorThrown);
        }
    });
}

jqueryUpImg.ashx文件内容:

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

using System;
using System.Web;

using System.IO;

public class jqueryUpImg : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        HttpFileCollection postedFile = context.Request.Files;
        HttpPostedFile file = postedFile[0];
        string uploadpath = HttpContext.Current.Server.MapPath("upFile\\" + @context.Request["name"] + "\\");  //上传路径

        if (file != null)
        {
            string filetype =Path.GetExtension(file.FileName).ToLower();
            filetype = filetype.ToLower();
            if (filetype == ".png" || filetype == ".jpg" || filetype == ".gif" || filetype == ".bmp" || filetype == ".jpeg" || filetype == ".icon") //文件类型
            {
                Random rd = new Random();

                string oldFileName = file.FileName;
                string fileNameStr = DateTime.Now.ToString("yyyyMMddhhmmssfff") + rd.Next(100, 999).ToString();
                string fileName = fileNameStr + filetype;
                string savepath = uploadpath + fileName;
                string width = @context.Request["width"];
                string height = @context.Request["height"];
                if (File.Exists(savepath))
                {
                    //context.Response.Write("0" + "$" + "当前图片名称已经存在,请更改!");
                    context.Response.Write("{\"status\" : \"error\", \"msg\" : \"当前图片名称已经存在,请更改!\"}");
                }
                else
                {
                    if (Directory.Exists(uploadpath) == false)//如果不存在就创建file文件夹
                    {
                        Directory.CreateDirectory(uploadpath);
                    }

                    file.SaveAs(savepath);

                    try
                    {
                        string[] widthStr = width.Split(',');
                        string[] heightStr = height.Split(',');

                        /*规定大小图片*/
                        string fileNameStr1 = DateTime.Now.ToString("yyyyMMddhhmmssfff") + rd.Next(1000, 9999).ToString();
                        string fileName1 = fileNameStr1 + filetype;
                        string newpath = uploadpath + fileName1;
                        ImageCut.MakeThumbnail(savepath, newpath, Convert.ToInt32(widthStr[0]), Convert.ToInt32(heightStr[0]), (heightStr[0] == "0" ? "W" : "Cut")); //进行切图

                        string fileNameStr2 = DateTime.Now.ToString("yyyyMMddhhmmssfff") + rd.Next(1000, 9999).ToString();
                        string fileName2 = fileNameStr2 + filetype;
                        string newpath1 = uploadpath + fileName2;
                        ImageCut.MakeThumbnail(newpath, newpath1, Convert.ToInt32(widthStr[1]), Convert.ToInt32(heightStr[1]), (heightStr[1] == "0" ? "W" : "Cut")); //进行切图

                        string fileNameStr3 = DateTime.Now.ToString("yyyyMMddhhmmssfff") + rd.Next(1000, 9999).ToString();
                        string fileName3 = fileNameStr3 + filetype;
                        string newpath2 = uploadpath + fileName3;
                        ImageCut.MakeThumbnail(newpath, newpath2, Convert.ToInt32(widthStr[2]), Convert.ToInt32(heightStr[2]), (heightStr[2] == "0" ? "W" : "Cut")); //进行切图

                        if (File.Exists(newpath))
                        {
                            if (savepath.Trim() != "")
                            {
                                string img = System.Configuration.ConfigurationManager.AppSettings["WebUrl"] + "upFile/" + @context.Request["name"] + "/" + fileName;
                                string imgBig = System.Configuration.ConfigurationManager.AppSettings["WebUrl"] + "upFile/" + @context.Request["name"] + "/" + fileName1;
                                string imgMiddle = System.Configuration.ConfigurationManager.AppSettings["WebUrl"] + "upFile/" + @context.Request["name"] + "/" + fileName2;
                                string imgSmall = System.Configuration.ConfigurationManager.AppSettings["WebUrl"] + "upFile/" + @context.Request["name"] + "/" + fileName3;
                                //context.Response.Write("1" + "$" + imgPath + "$" + imgSPath);
                                context.Response.Write("{\"status\" : \"success\", \"img\" : \"" + img + "\", \"imgBig\" : \"" + imgBig + "\", \"imgMiddle\" : \"" + imgMiddle + "\", \"imgSmall\" : \"" + imgSmall + "\"}");
                            }
                            else
                            {
                                //context.Response.Write("0" + "$" + "上传失败,请重试!");
                                context.Response.Write("{\"status\" : \"error\", \"msg\" : \"上传失败,请重试!\"}");
                            }
                            //存在文件
                        }
                        else
                        {
                            //不存在文件
                            context.Response.Write("0" + "$" + "上传失败,请重试!");
                            context.Response.Write("{\"status\" : \"error\", \"msg\" : \"上传失败,请重试!\"}");
                        }
                    }
                    catch
                    {
                        //图片切图错误
                        context.Response.Write("0" + "$" + "上传失败,请重试!");
                        context.Response.Write("{\"status\" : \"error\", \"msg\" : \"上传失败,请重试!\"}");
                    }
                }
            }
            else if (filetype == ".doc" || filetype == ".docx" || filetype == ".xls" || filetype == ".xlsx" || filetype == ".rar" || filetype == ".zip" || filetype == ".pdf")
            {
                Random rd = new Random();

                string oldFileName = file.FileName;
                string fileNameStr = DateTime.Now.ToString("yyyyMMddhhmmssfff") + rd.Next(100, 999).ToString();
                string fileName = fileNameStr + filetype;
                string savepath = uploadpath + fileName;

                if (File.Exists(savepath))
                {
                    //context.Response.Write("0" + "$" + "当前附件名称已经存在,请重新上传!");
                    context.Response.Write("{\"status\" : \"error\", \"msg\" : \"当前附件名称已经存在,请重新上传!\"}");
                }
                else
                {
                    if (Directory.Exists(uploadpath) == false)//如果不存在就创建file文件夹
                    {
                        Directory.CreateDirectory(uploadpath);
                    }

                    file.SaveAs(savepath);

                    if (File.Exists(savepath))
                    {
                        string filePath = System.Configuration.ConfigurationManager.AppSettings["WebUrl"] + "upFile/" + @context.Request["name"] + "/" + fileName;
                        //context.Response.Write("1" + "$" + filePath);
                        context.Response.Write("{\"status\" : \"success\", \"filePath\" : \"" + filePath + "\"}");
                    }
                    else
                    {
                        //不存在文件
                        //context.Response.Write("0" + "$" + "上传失败,请重试!");
                        context.Response.Write("{\"status\" : \"error\", \"msg\" : \"上传失败,请重试!\"}");
                    }
                }
            }
            else
            {
                //context.Response.Write("0" + "$" + "文件名格式不正确!");
                context.Response.Write("{\"status\" : \"error\", \"msg\" : \"文件名格式不正确!\"}");
            }
        }
        else
        {
            //context.Response.Write("0" + "$" + "上传失败,请重试!");
            context.Response.Write("{\"status\" : \"error\", \"msg\" : \"上传失败,请重试!\"}");
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

MakeThumbnail方法:

/// <summary>
/// 生成缩略图
/// </summary>
/// <param name="originalImagePath">源图路径(物理路径)</param>
/// <param name="thumbnailPath">缩略图路径(物理路径)</param>
/// <param name="width">缩略图宽度</param>
/// <param name="height">缩略图高度</param>
/// <param name="mode">生成缩略图的方式</param>
public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
{
    System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);
    int towidth = width;
    int toheight = height;
    int x = 0;
    int y = 0;
    int ow = originalImage.Width;
    int oh = originalImage.Height;

    switch (mode)
    {
        case "HW":
            //指定高宽缩放(可能变形)   
            break;
        case "W":
            //指定宽,高按比例
            toheight = originalImage.Height * width / originalImage.Width; break;
        case "H":
            //指定高,宽按比例
            towidth = originalImage.Width * height / originalImage.Height; break;
        case "Cut":
            //指定高宽裁减(不变形) 
            if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
            {
                oh = originalImage.Height;
                ow = originalImage.Height * towidth / toheight;
                y = 0; x = (originalImage.Width - ow) / 2;
            }
            else
            {
                ow = originalImage.Width; oh = originalImage.Width * height / towidth; x = 0; y = (originalImage.Height - oh) / 2;
            } break;
        default: break;
    }

    //新建一个bmp图片
    System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
    //新建一个画板  
    System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
    //设置高质量插值法
    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
    //设置高质量,低速度呈现平滑程度 
    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
    //清空画布并以透明背景色填充
    g.Clear(System.Drawing.Color.Transparent);
    //在指定位置并且按指定大小绘制原图片的指定部分
    g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
        new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel);
    try
    {
        //以jpg格式保存缩略图
        ImageFormat imgFormat = ImageFormat.Jpeg;
        if (originalImagePath.IndexOf("png") != -1)
        {
            imgFormat = ImageFormat.Png;
        }
        else if (originalImagePath.IndexOf("gif") != -1)
        {
            imgFormat = ImageFormat.Gif;
        }
        else if (originalImagePath.IndexOf("bmp") != -1)
        {
            imgFormat = ImageFormat.Bmp;
        }
        else
        {
            imgFormat = ImageFormat.Jpeg;
        }
        bitmap.Save(thumbnailPath, imgFormat);
    }
    catch (System.Exception e)
    {
        throw e;
    }
    finally
    {
        originalImage.Dispose(); bitmap.Dispose(); g.Dispose();
    }
}

« 上一篇下一篇 »

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。