上传图片

Posted on 2011-04-19 15:43  到了,明天  阅读(136)  评论(0)    收藏  举报

  /// <summary>
  /// 返回图片类型
  /// </summary>
  /// <param name="type"></param>
  /// <returns></returns>

 public static string UpFileType(string type)
    {

        string ft=string.Empty;
        if (type == "image/pjpeg")
        {
            ft = "jpg";
        }
        if (type == "image/jpeg")
        {
            ft = "jpg";
        }
        if (type == "image/gif")
            ft = "gif";
        if (type == "application/x-shockwave-flash")
            ft = "swf";
        if (type == "image/bmp")
            ft = "bmp";
        return ft;
    }   

 /// <summary>
    ///FileUpload上传图片,返回完整的相对的保存路径(含文件名、后缀).否则返回Empty""
    /// </summary>
    /// <param name="FileType">可以上传的文件类型</param>
    /// <param name="FileSize">可以上传的文件大小</param>
    /// <param name="FileUrl">文件保存的相对路径(不含文件名)</param>
    /// <param name="FileName">文件名,不含后缀.</param>
    /// <param name="fu">一个文件上传控件的ID</param>
    /// <returns>返回完整的相对的保存路径(含文件名、后缀).否则返回Empty</returns>

    public static string Img_Up(FileUpload fu, string[] FileType, int FileSize, string FileUrl,string FileName)
    {
        string SavaUrl = string.Empty;
        if (fu.HasFile)
        {
            bool type = true;
            string fileType = UpFileType(fu.PostedFile.ContentType.ToString());
            foreach (string a in FileType)
            {
                if (fileType == a.ToLower()) { type = false; }
            }
            if (type)
            {
                 Response.Write("图片格式不正确,只允许" + string.Join(",", FileType) + "!");
                 HttpContext.Current.Response.End();
            }
            if (fu.PostedFile.ContentLength > FileSize)
            {
                Response.Write("图片不能大于" + FileSize / 1024 + "K!");
                HttpContext.Current.Response.End();
            }
            if (!Directory.Exists(HttpContext.Current.Server.MapPath(FileUrl)))
            {
                Directory.CreateDirectory(HttpContext.Current.Server.MapPath(FileUrl));
            }
            //fso.CreateDirectory(FileUrl);  
            SavaUrl =FileUrl+ FileName+"." + fileType;
            fu.SaveAs(HttpContext.Current.Server.MapPath(SavaUrl));
        }
        return SavaUrl;
    }