zoukankan      html  css  js  c++  java
  • 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 "";
  • 相关阅读:
    cf D. Vessels
    cf C. Hamburgers
    zoj 3758 Singles' Day
    zoj 3777 Problem Arrangement
    zoj 3778 Talented Chef
    hdu 5087 Revenge of LIS II
    zoj 3785 What day is that day?
    zoj 3787 Access System
    判断给定图是否存在合法拓扑排序
    树-堆结构练习——合并果子之哈夫曼树
  • 原文地址:https://www.cnblogs.com/sky-net/p/3841609.html
Copyright © 2011-2022 走看看