C#上传图片保存并展示

7 篇文章 0 订阅
2 篇文章 0 订阅
<%@ Page Title="开放平台申请页面" Language="C#" MasterPageFile="~/MainMaster.master" AutoEventWireup="true" CodeFile="AldsApplyPage.aspx.cs" Inherits="AutoLogistics_AldsApplyPage" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
    <meta http-equiv="pragma" content="no-cache" />
    <meta http-equiv="Cache-Control" content="no-cache, must-revalidate" />
    <link rel="stylesheet" type="text/css" href="../css/viewer.min.css"/>
    <style type="text/css">
    .ui-jqgrid tr.jqgrow td {
        white-space: normal !important;
    }
    .ui-menu { position: absolute; width: 95px; }
    .ui-menu li a { height:22px; }

    <% if(AldsType == xxx.Objects.Enums.AldsType.Confirm) {%>
        #tab1 .ui-widget-header,.tipBg{
                background:#dcf3e5;
            }
    <%}else if(AldsType == xxx.Objects.Enums.AldsType.Rated){%> 
        #tab1 .ui-widget-header,.tipBg{
        background:#cee9fa;
    <% } %>
    
    .starClass{color:red;vertical-align:middle;}
    </style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <form id="aldsApplyPageForm" runat="server">
        <h3 class="h3title">开放平台接入申请</h3>
        <hr />
        <table>
            <tbody>
                <tr>
                    <td>申请主体</td>
                    <td>
                        <asp:DropDownList ID="DdlApplicantType" runat="server">
                            <asp:ListItem Text="个人" Value="0" Selected="True"></asp:ListItem>
                            <asp:ListItem Text="公司" Value="1" Selected="False"></asp:ListItem>
                        </asp:DropDownList>
                    </td>
                </tr>
                <tr>
                    <td>应用类型</td>
                    <td>
                        <asp:DropDownList ID="DdlUseType" runat="server">
                            <asp:ListItem Text="自用" Value="0" Selected="True"></asp:ListItem>
                            <asp:ListItem Text="多店共用" Value="1" Selected="False"></asp:ListItem>
                        </asp:DropDownList>
                    </td>
                </tr>
                <tr class="personalType">
                    <td>个人身份证扫描件</td>
                    <td>
                        <input type="file" id="personalCard" name="personalCard" />
                        <input id="uploadCardBtn" type="button" value="开始上传" />
                    </td>
                </tr>
                <tr class="personalType">
                    <td></td>
                    <td>
                        <!--img style="display:none;" class="imgView" width="200" id="imgpersonalCard" alt="" src="" /-->
                        <asp:Image CssClass="imgView" Width="200" ID="IPersonalCard" AlternateText="" ImageUrl="" runat="server" />
                    </td>
                </tr>
                <tr class="personalType">
                    <td>手持身份证照片</td>
                    <td>
                        <input type="file" id="personalPhoto" name="personalPhoto" />
                        <input id="uploadPhotoBtn" type="button" value="开始上传" />
                    </td>
                </tr>
                <tr class="personalType">
                    <td></td>
                    <td>
                        <!--img style="display:none;" class="imgView" width="200" id="imgpersonalPhoto" alt="" src="" /-->
                        <asp:Image CssClass="imgView" Width="200" ID="IPersonalPhoto" AlternateText="" ImageUrl="" runat="server" />
                    </td>
                </tr>
                <tr class="corpType">
                    <td>营业执照加章复印件</td>
                    <td>
                        <input type="file" id="corpCard" name="corpCard" />
                        <input id="uploadCorpCardBtn" type="button" value="开始上传" />
                    </td>
                </tr>
                <tr class="corpType">
                    <td></td>
                    <td>
                        <!--img style="display:none;" class="imgView" width="200" id="imgcorpCard" alt="" src="" /-->
                        <asp:Image CssClass="imgView" Width="200" ID="ICorpCard" AlternateText="" ImageUrl="" runat="server" />
                    </td>
                </tr>
                <tr>
                    <td>开发功能及目的</td>
                    <td>
                        <asp:TextBox TextMode="MultiLine" Width="400" ID="TBGoal" MaxLength="1000" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr class="corpType">
                    <td>法人姓名</td>
                    <td><asp:TextBox ID="TBCorpOwnerName" MaxLength="10" runat="server"></asp:TextBox></td>
                </tr>
                <tr class="corpType">
                    <td>法人联系方式</td>
                    <td><asp:TextBox ID="TBCropOwnerTel" MaxLength="15" runat="server"></asp:TextBox></td>
                </tr>
                <tr>
                    <td>开发者姓名</td>
                    <td><asp:TextBox ID="TBDevName" MaxLength="10" runat="server"></asp:TextBox></td>
                </tr>
                <tr>
                    <td>开发者联系方式</td>
                    <td><asp:TextBox ID="TBDevTel" MaxLength="15" runat="server"></asp:TextBox></td>
                </tr>
                <tr>
                    <td>店铺名</td>
                    <td><asp:TextBox ID="TBShopName" MaxLength="30" runat="server"></asp:TextBox></td>
                </tr>
                <tr id="trVerifiedResult">
                    <td>审核意见</td>
                    <td><asp:TextBox Enabled="false" ID="TBVerifiedResult" ForeColor="Red" Width="400" TextMode="MultiLine" MaxLength="1000" Text="" runat="server"></asp:TextBox></td>
                </tr>
                <tr>
                    <td></td>
                    <td><input id="saveBtn" type="button" value="提交" /></td>
                </tr>
            </tbody>
        </table>
    </form>
    <script src="../javascript/ajaxfileupload.js" type="text/javascript"></script>
    <script src="../javascript/viewer.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            (function()
            {
                setApplicantType();
                setImageContainer();
                setRemark();
            })();

            function setApplicantType() {
                if ($("#<% =DdlApplicantType.ClientID %>").val() == 0) {
                    $(".personalType").show();
                    $(".corpType").hide();
                } else {
                    $(".personalType").hide();
                    $(".corpType").show();
                }
            }

            function setImageContainer()
            {
                if ($("#<%=IPersonalCard.ClientID%>").prop("alt") == "")
                    $("#<%=IPersonalCard.ClientID%>").hide();
                else
                    $("#<%=IPersonalCard.ClientID%>").show();

                if ($("#<%=IPersonalPhoto.ClientID%>").prop("alt") == "")
                    $("#<%=IPersonalPhoto.ClientID%>").hide();
                else
                    $("#<%=IPersonalPhoto.ClientID%>").show();

                if ($("#<%=ICorpCard.ClientID%>").prop("alt") == "")
                    $("#<%=ICorpCard.ClientID%>").hide();
                else
                    $("#<%=ICorpCard.ClientID%>").show();
            }
            function setRemark()
            {
                if ($("#<%=TBVerifiedResult.ClientID%>").text() == "")
                {
                    $("#trVerifiedResult").hide();
                }
            }

            $("#<% =DdlApplicantType.ClientID %>").change(function () {
                setApplicantType();
            });

            
            
            $("#uploadCardBtn").button().click(function () {
                uploading("personalCard");
            });
            $("#uploadPhotoBtn").button().click(function () {
                uploading("personalPhoto");
            });
            $("#uploadCorpCardBtn").button().click(function () {
                uploading("corpCard");
            });
            $("#saveBtn").button().click(function () {
                var personalCard = $("#<%=IPersonalCard.ClientID%>").prop("alt");
                var personalPhoto = $("#<%=IPersonalPhoto.ClientID%>").prop("alt");
                var corpCard = $("#<%=ICorpCard.ClientID%>").prop("alt");
                var devGoal = $("#<%=TBGoal.ClientID%>").val();
                var ownerName = $("#<%=TBCorpOwnerName.ClientID%>").val();
                var ownerTel = $("#<%=TBCropOwnerTel.ClientID%>").val();
                var devName = $("#<%=TBDevName.ClientID%>").val();
                var devTel = $("#<%=TBDevTel.ClientID%>").val();
                var sName = $("#<%=TBShopName.ClientID%>").val();
                var appType = $("#<%=DdlApplicantType.ClientID%>").val();
                var verified = 0;
                var uType = $("#<%=DdlUseType.ClientID%>").val();
                
                if (personalCard == "" && appType == 0)
                {
                    popUpDialog("必须上传身份证扫描件");
                    return;
                }
                if (personalPhoto == "" && appType == 0)
                {
                    popUpDialog("必须上传手持身份证照片");
                    return;
                }
                if (corpCard == "" && appType == 1)
                {
                    popUpDialog("必须上传公司营业执照照片");
                    return;
                }
                if (devGoal == "")
                {
                    popUpDialog("开发功能及目的必填");
                    return;
                }
                if (ownerName == "" && appType == 1)
                {
                    popUpDialog("企业法人姓名必填");
                    return;
                }
                if (ownerTel == "" && appType == 1)
                {
                    popUpDialog("企业法人联系方式必填");
                    return;
                }
                if (devName == "")
                {
                    popUpDialog("开发人员姓名必填");
                    return;
                }
                if (devTel == "")
                {
                    popUpDialog("开发人员联系方式必填");
                    return;
                }

                var url = getCurrentUrl() + "method=Save";
                $.post(url, { pCard: personalCard, pPhoto: personalPhoto, cCard: corpCard, goal: devGoal, corpOwnerName: ownerName, corpOwnerTel: ownerTel, developerName: devName, developerTel: devTel, shopName: sName, applicantsType: appType, isVerified: verified, useType: uType })
                .done(function (myJsonResult) {
                    var data = $.evalJSON(myJsonResult);
                    ajaxResponseResult(data);
                })
                .fail(function (data) {
                    ajaxResponseResult(data);
                })
                .always(function (myJsonResult) {
                });
            });

            function popUpDialog(s)
            {
                $("<p>"+s+"</p>").dialog({
                    title: '保存提醒',
                    closeText: '关闭',
                    width: 300,
                    height: 200,
                    modal: true,
                    show: { effect: "fade", duration: 300 },
                    hide: { effect: "fade", duration: 300 },
                    buttons: {
                        关闭: function () {
                            $(this).dialog("close");
                        }
                    }
                });
            }

            function uploading(id)
            {
                if ($("#" + id).val() == "")
                    return;
                $.ajaxFileUpload //上传文件的组件
                (
                    {
                        url: getCurrentUrl() + "method=UploadFile",
                        fileElementId: id,
                        dataType: 'JSON',//这个要大写
                        success: function (data, status) {
                            var data = $.evalJSON(data);
                            ajaxResponseResult(data);
                            setImgSrc(id, data.rows);
                        },
                        error: function (data, status, e) {
                            var data = $.evalJSON(data);
                            ajaxResponseResult(data);
                        }
                    }
                );
            }

            function setImgSrc(id,imgName)
            {
                switch (id)
                {
                    case "personalCard":
                        $("#<%=IPersonalCard.ClientID%>").attr("src", "AldsApplyPage.aspx?method=ProcessRequestImg&random=" + Math.random() + "&imgName=" + imgName);
                        $("#<%=IPersonalCard.ClientID%>").attr("alt", imgName);
                        break;
                    case "personalPhoto":
                        $("#<%=IPersonalPhoto.ClientID%>").attr("src", "AldsApplyPage.aspx?method=ProcessRequestImg&random=" + Math.random() + "&imgName=" + imgName);
                        $("#<%=IPersonalPhoto.ClientID%>").attr("alt", imgName);
                        break;
                    case "corpCard":
                        $("#<%=ICorpCard.ClientID%>").attr("src", "AldsApplyPage.aspx?method=ProcessRequestImg&random=" + Math.random() + "&imgName=" + imgName);
                        $("#<%=ICorpCard.ClientID%>").attr("alt", imgName);
                        break;
                    default:
                        break;
                }
                setImageContainer();
            }

            $(".imgView").button().click(function () {
                $(".imgView").viewer();//这个,点击图片元素就给他放大
            });
        });
    </script>
</asp:Content>


ajaxFileUpload组件,无刷新上传图片:

https://github.com/carlcarl/AjaxFileUpload

viewer组件,点击看大图:

https://github.com/fengyuanchen/viewer


图片保存:

    public AjaxResponseResultObject UploadFile()
    {
        AjaxResponseResultObject arro = new AjaxResponseResultObject();

        HttpFileCollection files = Request.Files;
        HttpPostedFile file = files[0];
        if (file.ContentLength > 4194304) 
            return arro.CreateErrArro("图片上传失败,图片体积不能大于4M。");

        try
        {
            string fname = ImageUpload.ImageSave(Request);
            if (!string.IsNullOrEmpty(fname))
            {
                string extension = Path.GetExtension(fname);
                string imgName = fname.Substring(0, fname.IndexOf(extension));
                LogUploadImgManager.Insert(imgName, CurrentAccount.TaobaoUserId, extension);

                arro.rows = imgName;
                arro.PromptMsg = "图片上传成功。";
                arro.IsSuccess = true;
            }
            else
                return arro.CreateErrArro("没有保存任何图片。");
        }
        catch (Exception e)
        {
            LogWriter.WriteLog(e.ToString(), 1);
            arro.IsSuccess = false;
            arro.AlertMsg = string.Format("上传图片时出错。异常:{0}", e.Message);
        }
        return arro;
    }

    public class ImageUpload
    {
        /// <summary>
        /// 从request取出来并保存到配置的地方,返回包含扩展名的文件名
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static string ImageSave(HttpRequest request) 
        {
            if (request.Files.Count < 1)
                return null;
            HttpFileCollection files = request.Files;
            string path = Config.ImgUploadPath;
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            HttpPostedFile file = files[0];
            string extension = Path.GetExtension(file.FileName);
            string imgName = Guid.NewGuid().ToString();
            imgName = imgName.Replace("-","");
            string fullPath = path + '\\' + imgName + extension;
            file.SaveAs(fullPath);
            return imgName + extension;
        }
    }


图片读取:

因为图片比较隐私,为了不暴露图片地址,采用前端ajax请求,后端返回图片流的方法

    public AjaxResponseResultObject ProcessRequestImg()
    {
        if (CurrentAccount == null)
            return null;
        try
        {
            string imgName = Request["imgName"];
            LogUploadImgInfo info;
            if (Config.AdminNick.Equals(CurrentAccount.TaobaoUserNick))
                info = LogUploadImgManager.GetUploadImgInfoByAdmin(imgName);//去数据库查询是否此图属于查看者所有,如果是管理员则不受限制
            else
                info = LogUploadImgManager.GetUploadImgInfo(imgName, CurrentAccount.TaobaoUserId);
            if (info == null)
                return null;
            ImageShow.ImageWriteToResponse(Response, imgName, info.Extension);
        }
        catch (Exception e)
        {
            LogWriter.WriteLog(e.ToString(), 1);
        }
        return null;
    }

下面为读取图片并写入到响应:

    public class ImageShow
    {
        /// <summary>
        /// 通过ajax请求直接返回图片,设置到img标签的src
        /// </summary>
        /// <param name="response"></param>
        /// <param name="fname"></param>
        public static void ImageWriteToResponse(HttpResponse response,string fname,string extension)
        {
            MemoryStream ms = new MemoryStream();
            System.Drawing.Bitmap image = ReadFile(Config.ImgUploadPath + "//" + fname + extension);
            image.Save(ms, GetImageFormat(extension));
            response.ClearContent();
            response.ContentType = GetContentType(extension);
            response.BinaryWrite(ms.ToArray());
            response.End();
        }

        public static Bitmap ReadFile(string fpath)
        {
            FileStream fs = File.OpenRead(fpath); //OpenRead
            int filelength = 0;
            filelength = (int)fs.Length; //获得文件长度 
            Byte[] image = new Byte[filelength]; //建立一个字节数组 
            fs.Read(image, 0, filelength); //按字节流读取 
            Image result = Image.FromStream(fs);
            fs.Close();
            Bitmap bit = new Bitmap(result);
            return bit;
        }

        private static ImageFormat GetImageFormat(string extension)
        {
            switch (extension.ToLower())
            {
                case ".jpg":
                case ".jpeg":
                    return ImageFormat.Jpeg;
                case ".bmp":
                    return ImageFormat.Bmp;
                case ".png":
                    return ImageFormat.Png;
                default:
                    return null;
            }
        }

        private static string GetContentType(string extension)
        {
            switch (extension.ToLower())
            {
                case ".jpg":
                case ".jpeg":
                    return "image/jpeg";
                case ".bmp":
                    return "image/bmp";
                case ".png":
                    return "image/png";
                default:
                    return null;
            }
        }
    }




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值