上傳圖片用圖片文件的對象hash哈希值判斷圖片是否一樣,避免重復提交相同的圖片到服務器中


上傳圖片用圖片文件的對象hash哈希值判斷圖片是否一樣,避免重復提交相同的圖片到服務器中

前端:要用到一個插件,點擊下載

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>企業用戶后台管理系統 - 譚人才招聘系統</title>
    <meta http-equiv=Content-Type content="text/span; charset=gb2312" />
    <meta http-equiv=X-UA-Compatible content="IE=edge" />
    <script src="~/Scripts/jquery-1.8.0.min.js"></script>
    <script type="text/javascript" src="/Scripts/imgareaselect/ajaxfileupload.js"></script>
</head>
<body>
<form name="myform" method="post" id="myform" enctype="multipart/form-data">
 <input type="image" src="" width="185" height="75"  id="logo" />
<input id="image" class="logo_submit_f" type="file" name="image" onchange="ajaxfile();">
</form>

</body>
<script>    
    function ajaxfile() {
        if ($("#image").val() != '') {           
            $.ajaxFileUpload({
                url: '/Company/Home/UploadLogo',
                type: "post",
                secureuri: false, //是否需要安全協議,一般設置為false
                fileElementId: 'image', //文件上傳域的ID
                dataType: 'json', //返回值類型 一般設置為json
                data: { },
                success: function (data, status) {  //服務器成功響應處理函數                    
                    $('#logo').attr('src', data.FilePath);
                    $("input[name='logo']").val(data.FilePath);
                }
            })
        }
    }
   
</script>
</html>

  

后端:

        /// <summary>
        /// 上傳企業logo
        /// </summary>
        /// <returns></returns>
        public ActionResult UploadLogo()
        {
            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 = 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);
                }
            }
        }

 

做一個記錄,沒有高水平技術,簡簡單單寫個博客!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM