using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace Stat.Plugin
{
    public class UpFile
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="FileName"></param>
        /// <returns></returns>
        private static string GetNewFileName(string FileName)
        {//跟据文伯名产生一个由时间+随机数组成的一个新的文件名 
            string newfilename = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString()
            + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString()
            + DateTime.Now.Second.ToString() + DateTime.Now.Minute.ToString()
            + DateTime.Now.Millisecond.ToString()
                //+ rand.Next(1000).ToString() 
            + FileName.Substring(FileName.LastIndexOf("."), FileName.Length - FileName.LastIndexOf("."));
            return newfilename;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="p"></param>
        /// <param name="fileUpload"></param>
        /// <param name="ver"></param>
        /// <returns></returns>
        public static string FileUpAndReturnGetNewFileName(Page p, FileUpload fileUpload, string ver)
        {//根据上传页面,上传控件,标记,返回上传后新图片的名称 
            string newfilename = "";

            if (fileUpload.HasFile)
            {
                string fileExt =
                System.IO.Path.GetExtension(fileUpload.FileName);
                if (fileExt.ToLower() == ".jpg" || fileExt.ToLower() == ".gif")
                {
                    try
                    {
                        newfilename = ver + "_" + GetNewFileName(fileUpload.FileName.ToString()).ToLower();
                        if (File.Exists(p.Server.MapPath("~/Upfile/" + newfilename)) == false)
                        {
                            fileUpload.SaveAs(p.Server.MapPath("~/Upfile/" + newfilename));
                        }
                        else
                        {
                            Common.Alert("该文件已经存在!");
                            return null;
                        }
                    }
                    catch (Exception ex)
                    {
                        Common.Alert("错误：" + ex.Message.ToString());
                        return null;
                    }
                }
                else
                {
                    Common.Alert("只能上传图片!");
                    return null;
                }
            }
            else
            {
                Common.Alert("请选择图片!");
                return null;
            }

            return newfilename;
        }
    }
}
