Beispiel #1
0
        /// <summary>
        /// 保存远程文件到本地
        /// </summary>
        private string remoteSaveAs(Model.files model)
        {
            string upLoadPath     = Path.GetDirectoryName(model.file_path);
            string fullUpLoadPath = Utils.GetMapPath(upLoadPath); //上传目录的物理路径

            //检查上传的物理路径是否存在,不存在则创建
            if (!Directory.Exists(fullUpLoadPath))
            {
                Directory.CreateDirectory(fullUpLoadPath);
            }
            //检查目标文件是否存在
            if (Utils.FileExists(model.file_path))
            {
                //如果存在同名文件,检查MD5值是否一样
                string newFileHash = Utils.GetMD5HashFromFile(Utils.GetMapPath(model.file_path));
                if (newFileHash.ToLower() == model.file_md5.ToLower())
                {
                    return(model.file_path);
                }
            }
            //其余情况则下载文件
            WebClient client = new WebClient();

            try
            {
                client.DownloadFile(model.file_server + model.file_path, Utils.GetMapPath(model.file_path));
            }
            catch
            {
                return(string.Empty);
            }
            client.Dispose();
            return(model.file_path);
        }
Beispiel #2
0
        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Model.files GetModel(Int64 id)
        {
            StringBuilder strSql = new StringBuilder();

            strSql.Append("select top 1 id,file_name,file_path,file_md5,file_server,file_uptime,file_upuser,file_usetimes,file_state,file_type,file_endwith,file_fullpath");
            strSql.Append(" from " + databaseprefix + "files");
            strSql.Append(" where id=@id");
            SqlParameter[] parameters =
            {
                new SqlParameter("@id", SqlDbType.BigInt)
            };
            parameters[0].Value = id;

            Model.files model = new Model.files();
            DataSet     ds    = DbHelperSQL.Query(strSql.ToString(), parameters);

            if (ds.Tables[0].Rows.Count > 0)
            {
                return(DataRowToModel(ds.Tables[0].Rows[0]));
            }
            else
            {
                return(null);
            }
        }
Beispiel #3
0
        /// <summary>
        /// 保存远程文件到本地
        /// </summary>
        /// <param name="fileUri">URI地址</param>
        /// <returns>上传后的路径</returns>
        public string remoteSaveAs(string fileUri)
        {
            WebClient client  = new WebClient();
            string    fileExt = string.Empty; //文件扩展名,不含“.”

            if (fileUri.LastIndexOf(".") == -1)
            {
                fileExt = "gif";
            }
            else
            {
                fileExt = Utils.GetFileExt(fileUri);
            }
            string newFileName    = Utils.GetRamCode() + "." + fileExt; //随机生成新的文件名
            string upLoadPath     = GetUpLoadPath();                    //上传目录相对路径
            string fullUpLoadPath = Utils.GetMapPath(upLoadPath);       //上传目录的物理路径
            string newFilePath    = upLoadPath + newFileName;           //上传后的路径

            Model.files modelNewFile = new Model.files();               //新文件所需实体类
            //检查上传的物理路径是否存在,不存在则创建
            if (!Directory.Exists(fullUpLoadPath))
            {
                Directory.CreateDirectory(fullUpLoadPath);
            }

            try
            {
                client.DownloadFile(fileUri, fullUpLoadPath + newFileName);
                //如果是图片,检查是否需要打水印
                if (IsWaterMark(fileExt))
                {
                    switch (this.siteConfig.watermarktype)
                    {
                    case 1:
                        WaterMark.AddImageSignText(newFilePath, newFilePath,
                                                   this.siteConfig.watermarktext, this.siteConfig.watermarkposition,
                                                   this.siteConfig.watermarkimgquality, this.siteConfig.watermarkfont, this.siteConfig.watermarkfontsize);
                        break;

                    case 2:
                        WaterMark.AddImageSignPic(newFilePath, newFilePath,
                                                  this.siteConfig.watermarkpic, this.siteConfig.watermarkposition,
                                                  this.siteConfig.watermarkimgquality, this.siteConfig.watermarktransparency);
                        break;
                    }
                }
                //存储文件信息
                modelNewFile = new BLL.files().Add(newFilePath, userID);
            }
            catch
            {
                return(string.Empty);
            }
            client.Dispose();
            return(Utils.GetAppSettings("FileUrl") + modelNewFile.file_md5);
        }
Beispiel #4
0
        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(Model.files model)
        {
            StringBuilder strSql = new StringBuilder();

            strSql.Append("update " + databaseprefix + "files set ");
            strSql.Append("file_name=@file_name,");
            strSql.Append("file_path=@express_code,");
            strSql.Append("file_md5=@express_fee,");
            strSql.Append("file_server=@website,");
            strSql.Append("file_uptime=@remark,");
            strSql.Append("file_upuser=@sort_id,");
            strSql.Append("file_usetimes=@is_lock,");
            strSql.Append("file_state=@is_lock,");
            strSql.Append("file_type=@is_lock,");
            strSql.Append("file_endwith=@is_lock,");
            strSql.Append("file_fullpath=@file_fullpath");
            strSql.Append(" where id=@id");
            SqlParameter[] parameters =
            {
                new SqlParameter("@file_name",     SqlDbType.NVarChar,   50),
                new SqlParameter("@file_path",     SqlDbType.NVarChar,  255),
                new SqlParameter("@file_md5",      SqlDbType.NVarChar,   50),
                new SqlParameter("@file_server",   SqlDbType.NVarChar,   50),
                new SqlParameter("@file_uptime",   SqlDbType.DateTime),
                new SqlParameter("@file_upuser",   SqlDbType.Int,         4),
                new SqlParameter("@file_usetimes", SqlDbType.BigInt),
                new SqlParameter("@file_state",    SqlDbType.Int,         4),
                new SqlParameter("@file_type",     SqlDbType.Int,         4),
                new SqlParameter("@file_endwith",  SqlDbType.NVarChar,   10),
                new SqlParameter("@file_fullpath", SqlDbType.NVarChar,  255),
                new SqlParameter("@id",            SqlDbType.BigInt)
            };
            parameters[0].Value  = model.file_name;
            parameters[1].Value  = model.file_path;
            parameters[2].Value  = model.file_md5;
            parameters[3].Value  = model.file_server;
            parameters[4].Value  = model.file_uptime;
            parameters[5].Value  = model.file_upuser;
            parameters[6].Value  = model.file_usetimes;
            parameters[7].Value  = model.file_state;
            parameters[8].Value  = model.file_type;
            parameters[9].Value  = model.file_endwith;
            parameters[10].Value = model.file_fullpath;
            parameters[11].Value = model.id;

            int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);

            if (rows > 0)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Beispiel #5
0
 /// <summary>
 /// 得到一个对象实体
 /// </summary>
 public Model.files DataRowToModel(DataRow row)
 {
     Model.files model = new Model.files();
     if (row != null)
     {
         if (row["id"] != null && row["id"].ToString() != "")
         {
             model.id = int.Parse(row["id"].ToString());
         }
         if (row["file_name"] != null)
         {
             model.file_name = row["file_name"].ToString();
         }
         if (row["file_path"] != null)
         {
             model.file_path = row["file_path"].ToString();
         }
         if (row["file_md5"] != null)
         {
             model.file_md5 = row["file_md5"].ToString();
         }
         if (row["file_server"] != null)
         {
             model.file_server = row["file_server"].ToString();
         }
         if (row["file_uptime"] != null && row["file_uptime"].ToString() != "")
         {
             model.file_uptime = DateTime.Parse(row["file_uptime"].ToString());
         }
         if (row["file_upuser"] != null && row["file_upuser"].ToString() != "")
         {
             model.file_upuser = int.Parse(row["file_upuser"].ToString());
         }
         if (row["file_usetimes"] != null && row["file_usetimes"].ToString() != "")
         {
             model.file_usetimes = Int64.Parse(row["file_usetimes"].ToString());
         }
         if (row["file_state"] != null && row["file_state"].ToString() != "")
         {
             model.file_state = int.Parse(row["file_state"].ToString());
         }
         if (row["file_type"] != null && row["file_type"].ToString() != "")
         {
             model.file_type = int.Parse(row["file_type"].ToString());
         }
         if (row["file_endwith"] != null)
         {
             model.file_endwith = row["file_endwith"].ToString();
         }
         if (row["file_fullpath"] != null)
         {
             model.file_fullpath = row["file_fullpath"].ToString();
         }
     }
     return(model);
 }
Beispiel #6
0
        /// <summary>
        /// 增加一条数据
        /// </summary>
        public Int64 Add(Model.files model)
        {
            StringBuilder strSql = new StringBuilder();

            strSql.Append("insert into " + databaseprefix + "files(");
            strSql.Append("file_name,file_path,file_md5,file_server,file_uptime,file_upuser,file_usetimes,file_state,file_type,file_endwith,file_fullpath)");
            strSql.Append(" values (");
            strSql.Append("@file_name,@file_path,@file_md5,@file_server,@file_uptime,@file_upuser,@file_usetimes,@file_state,@file_type,@file_endwith,@file_fullpath)");
            strSql.Append(";select @@IDENTITY");
            SqlParameter[] parameters =
            {
                new SqlParameter("@file_name",     SqlDbType.NVarChar,   50),
                new SqlParameter("@file_path",     SqlDbType.NVarChar,  255),
                new SqlParameter("@file_md5",      SqlDbType.NVarChar,   50),
                new SqlParameter("@file_server",   SqlDbType.NVarChar,   50),
                new SqlParameter("@file_uptime",   SqlDbType.DateTime),
                new SqlParameter("@file_upuser",   SqlDbType.Int,         4),
                new SqlParameter("@file_usetimes", SqlDbType.BigInt),
                new SqlParameter("@file_state",    SqlDbType.Int,         4),
                new SqlParameter("@file_type",     SqlDbType.Int,         4),
                new SqlParameter("@file_endwith",  SqlDbType.NVarChar,   10),
                new SqlParameter("@file_fullpath", SqlDbType.NVarChar, 255)
            };
            parameters[0].Value  = model.file_name;
            parameters[1].Value  = model.file_path;
            parameters[2].Value  = model.file_md5;
            parameters[3].Value  = model.file_server;
            parameters[4].Value  = model.file_uptime;
            parameters[5].Value  = model.file_upuser;
            parameters[6].Value  = model.file_usetimes;
            parameters[7].Value  = model.file_state;
            parameters[8].Value  = model.file_type;
            parameters[9].Value  = model.file_endwith;
            parameters[10].Value = model.file_fullpath;

            object obj = DbHelperSQL.GetSingle(strSql.ToString(), parameters);

            if (obj == null)
            {
                return(0);
            }
            else
            {
                return(Convert.ToInt64(obj));
            }
        }
Beispiel #7
0
        /// <summary>
        /// 文件上传方法
        /// </summary>
        /// <param name="postedFile">文件流</param>
        /// <param name="isThumbnail">是否生成缩略图</param>
        /// <param name="isWater">是否打水印</param>
        /// <returns>上传后文件信息</returns>
        public string fileSaveAs(HttpPostedFile postedFile, bool isThumbnail, bool isWater)
        {
            try
            {
                string      fileExt              = Utils.GetFileExt(postedFile.FileName);                                    //文件扩展名,不含“.”
                int         fileSize             = postedFile.ContentLength;                                                 //获得文件大小,以字节为单位
                string      fileName             = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf(@"\") + 1); //取得原文件名
                string      newFileName          = Utils.GetRamCode() + "." + fileExt;                                       //随机生成新的文件名
                string      newThumbnailFileName = "thumb_" + newFileName;                                                   //随机生成缩略图文件名
                string      upLoadPath           = GetUpLoadPath();                                                          //上传目录相对路径
                string      fullUpLoadPath       = Utils.GetMapPath(upLoadPath);                                             //上传目录的物理路径
                string      newFilePath          = upLoadPath + newFileName;                                                 //上传后的路径
                string      newThumbnailPath     = upLoadPath + newThumbnailFileName;                                        //上传后的缩略图路径
                Model.files modelThumbnail       = new Model.files();                                                        //缩略图所需实体类
                Model.files modelNewFile         = new Model.files();                                                        //新上传文件所需实体类

                //检查文件扩展名是否合法
                if (!CheckFileExt(fileExt))
                {
                    return("{\"status\": 0, \"msg\": \"不允许上传" + fileExt + "类型的文件!\"}");
                }

                //检查文件大小是否合法
                if (!CheckFileSize(fileExt, fileSize))
                {
                    return("{\"status\": 0, \"msg\": \"文件超过限制的大小!\"}");
                }

                //检查上传的物理路径是否存在,不存在则创建
                if (!Directory.Exists(fullUpLoadPath))
                {
                    Directory.CreateDirectory(fullUpLoadPath);
                }

                //保存新文件
                postedFile.SaveAs(fullUpLoadPath + newFileName);

                //如果是图片,检查图片是否超出最大尺寸,是则裁剪
                if (IsImage(fileExt) && (this.siteConfig.imgmaxheight > 0 || this.siteConfig.imgmaxwidth > 0))
                {
                    Thumbnail.MakeThumbnailImage(fullUpLoadPath + newFileName, fullUpLoadPath + newFileName,
                                                 this.siteConfig.imgmaxwidth, this.siteConfig.imgmaxheight);
                }

                //如果是图片,检查是否需要生成缩略图,是则生成
                if (IsImage(fileExt) && isThumbnail && this.siteConfig.thumbnailwidth > 0 && this.siteConfig.thumbnailheight > 0)
                {
                    Thumbnail.MakeThumbnailImage(fullUpLoadPath + newFileName, fullUpLoadPath + newThumbnailFileName,
                                                 this.siteConfig.thumbnailwidth, this.siteConfig.thumbnailheight, this.siteConfig.thumbnailmode);
                    //存储文件信息
                    modelThumbnail = new BLL.files().Add(newThumbnailPath, userID);
                }
                else
                {
                    newThumbnailPath = newFilePath; //不生成缩略图则返回原图
                }

                //如果是图片,检查是否需要打水印
                if (IsWaterMark(fileExt) && isWater)
                {
                    switch (this.siteConfig.watermarktype)
                    {
                    case 1:
                        WaterMark.AddImageSignText(newFilePath, newFilePath,
                                                   this.siteConfig.watermarktext, this.siteConfig.watermarkposition,
                                                   this.siteConfig.watermarkimgquality, this.siteConfig.watermarkfont, this.siteConfig.watermarkfontsize);
                        break;

                    case 2:
                        WaterMark.AddImageSignPic(newFilePath, newFilePath,
                                                  this.siteConfig.watermarkpic, this.siteConfig.watermarkposition,
                                                  this.siteConfig.watermarkimgquality, this.siteConfig.watermarktransparency);
                        break;
                    }
                }

                //存储文件信息
                modelNewFile = new BLL.files().Add(newFilePath, userID);
                if (string.IsNullOrEmpty(modelThumbnail.file_path))
                {
                    modelThumbnail = modelNewFile;
                }

                //处理完毕,返回JOSN格式的文件信息
                return("{\"status\": 1, \"msg\": \"上传文件成功!\", \"name\": \""
                       + modelNewFile.file_name + "\", \"path\": \"" + Utils.GetAppSettings("FileUrl") + modelNewFile.file_md5 + "\", \"thumb\": \""
                       + Utils.GetAppSettings("FileUrl") + modelThumbnail.file_md5 + "\", \"size\": " + fileSize + ", \"ext\": \"" + fileExt + "\"}");
            }
            catch
            {
                return("{\"status\": 0, \"msg\": \"上传过程中发生意外错误!\"}");
            }
        }
Beispiel #8
0
 /// <summary>
 /// 根据MD5值下载文件并显示
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 protected void Page_Load(object sender, EventArgs e)
 {
     try
     {
         //获得来源参数
         string FileHashValue = HttpContext.Current.Request.Url.Query.ToString();
         if (FileHashValue.StartsWith("?"))
         {
             FileHashValue = FileHashValue.Substring(1);
         }
         //判断来源HASH是否为空
         if (string.IsNullOrEmpty(FileHashValue))
         {
             Response.End();
         }
         //判断来源Hash是否存在于缓存
         Model.files model = CacheHelperRedis.Get <Model.files>(fileCacheName, FileHashValue);
         BLL.files   bll   = new BLL.files();
         if (model == null)
         {
             model = bll.GetModel(FileHashValue);
             if (model != null)
             {
                 //写入缓存
                 CacheHelperRedis.Insert(fileCacheName, FileHashValue, model);
             }
         }
         //根据文件信息下载文件
         if (model != null)
         {
             //增加文件访问次数
             bll.UpdateField(model.id, "file_usetimes=file_usetimes+1");
             //检测是否被禁用或者删除
             if (model.file_state != -1)
             {
                 //从原始服务器上下载文件
                 remoteSaveAs(model);
                 if (model.file_type == 0)
                 {
                     //如果是图片类型则进行缓存控制并输出
                     string suffix = Utils.GetFileExt(model.file_path);
                     Response.ContentType = string.Format("image/{0}", suffix.ToLower().Equals("png") ? "x-png" : suffix);
                     DateTime contentModified = System.IO.File.GetLastWriteTime(Utils.GetMapPath(model.file_path));
                     if (IsClientCached(contentModified))
                     {
                         Response.StatusCode      = 304;
                         Response.SuppressContent = true;
                     }
                     else
                     {
                         Response.Cache.SetETagFromFileDependencies();
                         Response.Cache.SetAllowResponseInBrowserHistory(true);
                         Response.Cache.SetLastModified(contentModified);
                         FileStream fs     = new FileStream(Utils.GetMapPath(model.file_path), FileMode.Open, FileAccess.Read);
                         byte[]     byData = new byte[fs.Length];
                         fs.Read(byData, 0, byData.Length);
                         fs.Close();
                         System.IO.MemoryStream ms  = new System.IO.MemoryStream(byData);
                         System.Drawing.Image   img = System.Drawing.Image.FromStream(ms);
                         img.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                         Response.BinaryWrite(ms.ToArray()); //新增内容
                         img.Dispose();
                     }
                 }
                 else
                 {
                     //其它类型文件则直接提供下载
                     Response.Clear();
                     Response.Buffer = true;
                     Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(model.file_name, System.Text.Encoding.UTF8));
                     Response.WriteFile(Server.MapPath(model.file_path));
                     Response.Flush();
                     Response.Close();
                 }
             }
         }
         Response.End();
     }
     catch
     {
         Response.End();
     }
 }
Beispiel #9
0
        /// <summary>
        /// 增加一条数据(根据文件地址)
        /// </summary>
        /// <param name="fileUrl"></param>
        /// <param name="userID"></param>
        /// <returns></returns>
        public Model.files Add(string fileUrl, int userID = 0, bool neednew = false)
        {
            string filePath = Utils.GetMapPath(fileUrl);

            Model.files model = new Model.files();
            model.file_name     = Path.GetFileName(filePath);
            model.file_fullpath = Path.GetDirectoryName(filePath);
            model.file_path     = fileUrl;
            string fileExtension = Path.GetExtension(filePath);

            model.file_endwith = fileExtension;
            if (fileExtension.ToLower() == ".jpg" || fileExtension.ToLower() == ".jpeg" || fileExtension.ToLower() == ".png" || fileExtension.ToLower() == ".gif")
            {
                model.file_type = 0;
            }
            else if (fileExtension.ToLower() == ".rar" || fileExtension.ToLower() == ".zip" || fileExtension.ToLower() == ".7z")
            {
                model.file_type = 1;
            }
            else if (fileExtension.ToLower() == ".xls" || fileExtension.ToLower() == ".xlsx" || fileExtension.ToLower() == ".doc" || fileExtension.ToLower() == ".docx")
            {
                model.file_type = 2;
            }
            else
            {
                model.file_type = 3;
            }
            model.file_md5      = Utils.GetMD5HashFromFile(filePath);
            model.file_server   = Utils.GetAppSettings("LocalHost");
            model.file_state    = 0;
            model.file_uptime   = DateTime.Now;
            model.file_upuser   = userID;
            model.file_usetimes = 0;
            Int64 modelID = GetModeID(model.file_md5);

            if (modelID > 0)
            {
                Model.files modelold = GetModel(modelID);
                if (!neednew)
                {
                    //检查原文件是否存在,存在则删除新文件,不存在则记录
                    if (File.Exists(Utils.GetMapPath(modelold.file_path)))
                    {
                        if (Utils.GetMD5HashFromFile(Utils.GetMapPath(modelold.file_path)).ToLower() == modelold.file_md5)
                        {
                            File.Delete(Utils.GetMapPath(model.file_path));
                            return(modelold);
                        }
                        else
                        {
                            Delete(modelold.id);
                        }
                    }
                    else
                    {
                        Delete(modelold.id);
                    }
                }
                else
                {
                    //检查原文件是否存在,存在则删除,仅保留新文件
                    if (File.Exists(Utils.GetMapPath(modelold.file_path)))
                    {
                        File.Delete(Utils.GetMapPath(modelold.file_path));
                    }
                    Delete(modelold.id);
                }
            }
            model.id = Add(model);
            return(model);
        }
Beispiel #10
0
        /// <summary>
        /// 增加一条数据(判断HASH值是否存在)
        /// </summary>
        public Int64 Add(Model.files model)
        {
            Int64 modelID = GetModeID(model.file_md5);

            return(modelID > 0 ? modelID : dal.Add(model));
        }
Beispiel #11
0
 /// <summary>
 /// 更新一条数据
 /// </summary>
 public bool Update(Model.files model)
 {
     return(dal.Update(model));
 }