我试图从用户在我的web应用程序上传的图像的字节数组中创建一个MD5字符串..这是因为我想图像分散在不同的文件夹中。 而我不必使用userID作为文件夹名称。看起来更专业。创建上传图像的MD5哈希
结果会是这样的:
/images/ 'first-two-char-of-md5'/'the-complete-md5-string'.[jpg,png,bmp....]
这听起来是一个很好的解决方案来处理图像?
所以。 我的代码(东西从互联网上。):
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
if (CheckFileType(FileUpload1.FileName))
{
const int BUFFER_SIZE = 255;
Byte[] Buffer = new Byte[BUFFER_SIZE];
Stream theStream = FileUpload1.PostedFile.InputStream;
nBytesRead = theStream.Read(Buffer, 0, BUFFER_SIZE);
System.Text.ASCIIEncoding ASCIIEncoding = new ASCIIEncoding();
System.Text.UTF8Encoding utf8 = new UTF8Encoding();
//Just trying some stuff to see the output...
Label1.Text = ASCIIEncoding.GetString(CalculateMD5(theStream)) + "<br>" + utf8.GetString(CalculateMD5(theStream)) + "<br>" + Convert.ToBase64String(CalculateMD5(theStream));
}
}
}
private static byte[] _emptyBuffer = new byte[0];
public static byte[] CalculateMD5(Stream stream)
{
return CalculateMD5(stream, 64 * 1024);
}
public static byte[] CalculateMD5(Stream stream, int bufferSize)
{
MD5 md5Hasher = MD5.Create();
byte[] buffer = new byte[bufferSize];
int readBytes;
while ((readBytes = stream.Read(buffer, 0, bufferSize)) > 0)
{
md5Hasher.TransformBlock(buffer, 0, readBytes, buffer, 0);
}
md5Hasher.TransformFinalBlock(_emptyBuffer, 0, 0);
return md5Hasher.Hash;
}
结果。我从“calculateMD5()”得到一些输出,但是当我试图把它放到label1。看看发生了什么。只有一堆奇特的人物。 我在这里做错了什么?我希望它是htmlsafe ... a-z,A-Z,只有0-9。
谢谢!关于具有相同图像的2个用户。你认为有可能将userID添加到_emptybuffer字节[],在我的情况是空的(我认为),添加盐? – Easyrider 2012-01-10 11:59:46
是的,这应该工作。 MD5使用校验和来计算最终的散列,'TransformFinalBlock'是一种说法'这里是最后一个数据,并且完成散列操作'。或者,您可以将任何其他数据写入到传递给'CalculateMD5'的流的末尾(可能会先将图像数据读入中间的'MemoryStream',追加额外的数据并将'MemoryStream'传递给'CalculateMD5' )。 – mdm 2012-01-10 13:26:03