业务场景:
因需要对上传的图片与已上传的图片进行判重。
思路:
将文件转换为MD5值,比较值是否重复
业务方法:
/**
* 验证证还是重复
* @param photo 判重文件
* @param realPath 文件上传目录(需要与目录中进行比较)
* @return
* @throws Exception
*/
private String verification(String photo,String realPath, String extension)throws Exception {
String message = "";
String photoMd5 = ConvertMD5Tools.getMD5(photo);
File file = new File(realPath);
String[] filelist = file.list();
for (int j = 0; j < filelist.length; j++) {
File readfile = new File(realPath + "\\" + filelist[j]);
if (!readfile.isDirectory()) {
String absolutepath = readfile.getAbsolutePath();
String photoFileMd5 = ConvertMD5Tools.getMD5(absolutepath);
if (photoFileMd5.equals(photoMd5)) {
message = photo
+ "与" + absolutepath.substring((absolutepath.lastIndexOf("\\") + 1), absolutepath.length())
+ "文件内容一样!";
break;
}
}
}
if (!"".equals(message)) {
return message;
}
return message;
}
ConvertMD5Tools.java 转md5工具类:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class ConvertMD5Tools {
//通过图片本地路径拿到MD5
public static String getMD5(String imagePath) throws NoSuchAlgorithmException, IOException {
InputStream in = new FileInputStream(new File(imagePath));
StringBuffer md5 = new StringBuffer();
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] dataBytes = new byte[1024];
int nread = 0;
while ((nread = in.read(dataBytes)) != -1) {
md.update(dataBytes, 0, nread);
}
byte[] mdbytes = md.digest();
// convert the byte to hex format
for (int i = 0; i < mdbytes.length; i++) {
md5.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
}
in.close();
return md5.toString().toLowerCase();
}
}