• MVC实现上传图片的方法


    Form提交时,须注意form需要添加属性enctype="multipart/form-data",否则Request.Files.Count=0,无法上传图片。

    cshtml代码:

    <form id="form1" name="form1" action="SavaeTopicType.aspx" method="post" enctype="multipart/form-data">
    </form>

    cs代码:

            public bool ValidateImg(string imgName)
            {
                string[] imgType = new string[] { "gif", "jpg", "png", "bmp" };
    
                int i = 0;
                bool blean = false;
                string message = string.Empty;
    
                //判断是否为Image类型文件
                while (i < imgType.Length)
                {
                    if (imgName.Equals(imgType[i].ToString()))
                    {
                        blean = true;
                        break;
                    }
                    else if (i == (imgType.Length - 1))
                    {
                        break;
                    }
                    else
                    {
                        i++;
                    }
                }
                return blean;
            }
    
            public string upLoadImg(string fileName)
            {
                //上传和返回(保存到数据库中)的路径
                string uppath = string.Empty;
                string savepath = string.Empty;
                if (Request.Files.Count > 0)
                {
                    HttpPostedFileBase imgFile = Request.Files[fileName];
                    if (imgFile != null)
                    {
                        //创建图片新的名称
                        string nameImg = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                        //获得上传图片的路径
                        string strPath = imgFile.FileName;
                        //获得上传图片的类型(后缀名)
                        string type = strPath.Substring(strPath.LastIndexOf(".") + 1).ToLower();
                        if (ValidateImg(type))
                        {
                            //拼写数据库保存的相对路径字符串
                            savepath = "..\UpImgs\";
                            savepath += nameImg + "." + type;
                            //拼写上传图片的路径
                            uppath = Server.MapPath("~/UpImgs/");
                            uppath += nameImg + "." + type;
                            //上传图片
                            imgFile.SaveAs(uppath);
                        }
                        return savepath;
                    }
                }
                return "";
  • 相关阅读:
    「枫桥夜泊」一诗
    走遍亚洲 —— 泰国
    走遍亚洲 —— 泰国
    暴露年龄
    暴露年龄
    插入排序(insertion sort)
    开机黑屏 仅仅显示鼠标 电脑黑屏 仅仅有鼠标 移动 [已成功解决]
    OpenCV For iOS 1:&#160;连接OpenCV 3.0
    插入排序
    [hadoop系列]Pig的安装和简单演示样例
  • 原文地址:https://www.cnblogs.com/sky-net/p/3841609.html
Copyright © 2020-2023  润新知