標籤:public filename 根據 path length 數組 format content his
上傳圖片用圖片檔案的對象hash雜湊值判斷圖片是否一樣,避免重複提交相同的圖片到伺服器中
/// <summary> /// 上傳企業logo /// </summary> /// <returns></returns> public ActionResult UploadLogo(string comid) { HttpFileCollection files = System.Web.HttpContext.Current.Request.Files; if (files.Count == 0) return Json("沒有沒檔案", JsonRequestBehavior.AllowGet); MD5 hash = new MD5CryptoServiceProvider(); /**計算指定stream對象的雜湊值**/ byte[] bytehashValue = hash.ComputeHash(files[0].InputStream); var HashData = BitConverter.ToString(bytehashValue).Replace("-", ""); var FileExtension = Path.GetExtension(files[0].FileName); var filename = comid + "_" + HashData + FileExtension; var virtualpath = string.Format("/Upload/Logo/{0}/{1}", DateTime.Now.ToString("yyyyMMdd"), filename); //將虛擬路勁轉換成物理路勁 var fullpath = Server.MapPath(virtualpath); var path = Path.GetDirectoryName(fullpath); if (!Directory.Exists(path)) Directory.CreateDirectory(path); if (!System.IO.File.Exists(fullpath)) files[0].SaveAs(fullpath); var FileSize = this.FileSize(files[0].ContentLength); return Json(new { FileName = filename, FilePath = virtualpath, FileSize = FileSize }, "text/html", JsonRequestBehavior.AllowGet); } /// <summary> /// 計算檔案大小 /// </summary> /// <param name="bytes"></param> /// <returns></returns> public string FileSize(long bytes) { long kblong = 1024; long mblong = 1024 * 1024; if (bytes < kblong) return decimal.Round(decimal.Divide(bytes, kblong), 2).ToString() + "KB"; else return decimal.Round(decimal.Divide(bytes, mblong), 2).ToString() + "MB"; }
擷取檔案的hash雜湊值方法:
/// <summary> /// 計算檔案的hash值 用於比較兩個檔案是否相同 /// </summary> /// <param name="filePath">檔案路徑</param> /// <returns>檔案hash值</returns> public static string GetFileHash(string filePath) { //建立一個雜湊演算法對象 using (HashAlgorithm hash = HashAlgorithm.Create()) { using (FileStream file = new FileStream(filePath, FileMode.Open)) { //雜湊演算法根據文本得到雜湊碼的位元組數組 byte[] hashByte= hash.ComputeHash(file); //將位元組數組裝換為字串 return BitConverter.ToString(hashByte); } } }
做一個記錄,沒有高水平技術,簡簡單單寫個部落格!
上傳圖片用圖片檔案的對象hash雜湊值判斷圖片是否一樣,避免重複提交相同的圖片到伺服器中