上传图片用图片文件的对象hash哈希值判断图片是否一样,避免重复提交相同的图片到服务器中
前端:要用到一个插件,点击下载
企业用户后台管理系统 - 谭人才招聘系统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', );
$("input[name='logo']").val();
}
})
}
}
后端:
///
/// 上传企业logo
///
///
public ActionResult UploadLogo()
{
HttpFileCollection files = .Request.Files;
if ( == 0) return Json("没有没文件", );
MD5 hash = new MD5CryptoServiceProvider();
/**计算指定stream对象的哈希值**/
byte[] bytehashValue = (files[0].InputStream);
var HashData = (bytehashValue).Replace("-", "");
var FileExtension = (files[0].FileName);
var filename = HashData + FileExtension;
var virtualpath = string.Format("/Upload/Logo/{0}/{1}", ("yyyyMMdd"), filename);
//将虚拟路劲转换成物理路劲
var fullpath = Server.MapPath(virtualpath);
var path = (fullpath);
if (!(path))
(path);
if (!(fullpath))
files[0].SaveAs(fullpath);
var FileSize = (files[0].ContentLength);
return Json(new { FileName = filename, FilePath = virtualpath, FileSize = FileSize }, "text/html", );
}
///
/// 计算文件大小
///
///
///
public string FileSize(long bytes)
{
long kblong = 1024;
long mblong = 1024 * 1024;
if (bytes < kblong)
return ((bytes, kblong), 2).ToString() + "KB";
else
return ((bytes, mblong), 2).ToString() + "MB";
}
获取文件的hash哈希值方法:
///
/// 计算文件的hash值 用于比较两个文件是否相同
///
/// 文件路径
/// 文件hash值
public static string GetFileHash(string filePath)
{
//创建一个哈希算法对象
using (HashAlgorithm hash = ())
{
using (FileStream file = new FileStream(filePath, ))
{
//哈希算法根据文本得到哈希码的字节数组
byte[] hashByte= (file);
//将字节数组装换为字符串
return (hashByte);
}
}
}
做一个记录,没有高水平技术,简简单单写个博客!