Input 的 file 文件控件 + C# 的 ashx 文件 利用Ajax方法具有返回值 上传多张图片(不是form表单提交)

一:Html页面代码

<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script src="Js/jquery-1.11.1.min.js" type="text/javascript" charset="utf-8"></script>
    <title></title>
</head>
<body>
    <form id="fileForm" enctype="multipart/form-data">
        <%--产品Id--%>
        <input id="hidProId" type="hidden" />
        <div style="margin: 20px auto; text-align: center">
            <input id="imgFile" name="imgFile" type="file" multiple="multiple" />
            <a id="save" class="btn b btn_edit">提交</a>
        </div>
        <div id="imgrq" style="width: 100%; height: 100%">
        </div>
    </form>


    <%--proId--%>
    <script type="text/javascript">
        //产品Id
        var proId = parent.$("#addImgFrame").attr("data-id");
        //图片展示
        $("#imgFile").change(function () {
            var filedx = 0;
            for (var i = 0, j = this.files.length; i < j; i++) {
                $("#imgrq").append("<img  src=\"" + window.URL.createObjectURL(this.files[i]) + "\" width=\"80\" height=\"80\" />");
            }
        });
       //点击上传保存
        $("#save").click(function () {
            var form = new FormData($("#fileForm")[0]);
            $.ajax({
                url: "File.ashx?proId=" + proId,
                type: "post",
                data: form,
                xhrFields: { withCredentials: true },
                crossDomain: true,
                async: false,
                cache: false,
                contentType: false,
                processData: false,
                dataType: "json",
                success: function (data) {
                    if (data.Result) {
                        alert("图片上传成功!");
                    }
                    else {
                        alert(data.Msg);
                    }
                },
                error: function (data) {
                    alert(data);
                }
            })
        })
    </script>
</body>

二:ashx一般处理程序后台代码

public class File : IHttpHandler
{
    //文件暂时保存目录路径
    string Save_Path = "~/Images/";
    //文件新保存目录路径名
    string New_Save_Path = CS.Config.productImgAddress;
    //ProId产品Id
    string Pro_Id = "";
    public void ProcessRequest(HttpContext context)
    {
        /*
         * 1:先保存临时目录
         * 2.后移动到正式目录
         * 3:删除原文件
         * 4:将产品对应的图片添加到数据库中
         *
         */
        Pro_Id = context.Request.QueryString["proId"].toString().Trim();
        ExcuteResult result = new ExcuteResult();
        if (context.Request.Files.Count == 0)
        {
            result.Result = false;
            result.Msg = "文件为空!";
            ResponseMessage(context, result);
        }
        string url = context.Request.Path.Substring(0, context.Request.Path.LastIndexOf("/") + 1);
        //定义允许上传的文件扩展名
        List<string> typeList = new List<string> { "jpg", "jpeg", "png", "bmp", "gif" };
        //最大文件大小(100兆)
        int maxSize = 1024 * 1024 * 50;
        string allNames = "";
        for (int i = 0; i < context.Request.Files.Count; i++)
        {
            HttpPostedFile imgFile = context.Request.Files[i];
            if (imgFile == null)
            {
                result.Result = false;
                result.Msg = "请选择文件!";
                ResponseMessage(context, result);
            }
            //文件名
            string fileName = imgFile.FileName;
            //文件扩展名
            string fileExt = Path.GetExtension(fileName).ToLower();
            if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize)
            {
                result.Result = false;
                result.Msg = "单张图片最大为50M!";
                ResponseMessage(context, result);
            }
            if (fileName.IndexOf(".") <= 0)
            {
                result.Result = false;
                result.Msg = "文件格式错误!";
                ResponseMessage(context, result);
            }
            //文件类型
            string fileType = fileName.Substring(fileName.LastIndexOf(".") + 1);
            if (typeList.Find(a => a == fileType) == null)
            {
                result.Result = false;
                result.Msg = "只允许上传 gif,jpg,jpeg,png,bmp 类型图片!";
                ResponseMessage(context, result);
            }
            //获取本地路径
            string dirPath = context.Server.MapPath(Save_Path);
            //判断文件夹是否存在
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
            fileName = Guid.NewGuid().ToString("N") + fileName;
            string filePath = dirPath + fileName;
            imgFile.SaveAs(filePath);
            //2.移动图片
            bool moveResult = MovePic(fileName);
            if (!moveResult)
            {
                result.Result = false;
                result.Msg = "图片移动失败!";
                ResponseMessage(context, result);
            }
            //3.删除原文件
            if (System.IO.File.Exists(filePath))
            {
                System.IO.File.Delete(filePath);
            }
            allNames += fileName + ",";
        }
        allNames = allNames.Substring(0, allNames.Length - 1);
        if (!string.IsNullOrEmpty(allNames))
        {
            //4.保存到数据库
            if (AddProPic(allNames))
            {
                result.Result = true;
                result.Msg = "上传成功!";
                ResponseMessage(context, result);
            }
            else
            {
                result.Result = false;
                result.Msg = "数据库保存失败!";
                ResponseMessage(context, result);
            }
        }
    }

    /// <summary>
    /// 返回值
    /// </summary>
    /// <param name="context"></param>
    /// <param name="result"></param>
    public void ResponseMessage(HttpContext context, ExcuteResult result)
    {
        context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
        context.Response.Write(JsonConvert.SerializeObject(result));
        context.Response.End();
    }
    /// <summary>
    /// 移动图片
    /// </summary>
    /// <param name="picName"></param>
    public bool MovePic(string picName)
    {
        return CS.FolderConfig.MoveFile(picName, New_Save_Path + "/" + Pro_Id + "");
    }

    /// <summary>
    /// 保存图片到数据库
    /// </summary>
    /// <param name="picName"></param>
    /// <returns></returns>
    public bool AddProPic(string picName)
    {
        //传过来的参数产品Id
        int proId = Pro_Id.toString(0);
        string imgs = picName;
        return new CS.product_imgs { pro_id = proId, img = imgs }.AddProductImg();
    }

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

猜你喜欢

转载自blog.csdn.net/liuchang19950703/article/details/80897952
今日推荐