更新时间:2024-06-18 GMT+08:00
生成MD5值
媒资上传和更新
调用创建媒资:上传方式和视频更新接口时,可以通过“video_md5”设置媒资文件的MD5值。设置后,OBS会对媒资的MD5值进行检验,具体可参考设置对象属性。
该MD5值是经过标准的MD5哈希算法计算后,再进行base64编码的。示例代码如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
import org.apache.commons.codec.binary.Base64; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class VodDemoObsCheckMd5 { public String md5Generate4ObsCheck(String fileUrl) throws IOException, NoSuchAlgorithmException { String md5Content = null; if ((fileUrl != null) && (fileUrl.length() != 0)) { File file = new File(fileUrl); if (!file.exists()) { System.out.println("文件不存在"); } else if (file.isDirectory()) { System.out.println(file.getCanonicalPath() + "是一个目录,无法计算"); } else { FileInputStream fis = new FileInputStream(file); DigestInputStream dis = new DigestInputStream(fis, MessageDigest.getInstance("MD5")); byte[] buffer = new byte[8192]; while (dis.read(buffer) > 0) { } md5Content = new String(Base64.encodeBase64( dis.getMessageDigest().digest())); fis.getChannel().position(0L); System.out.println("该文件MD5为: " + md5Content); fis.close(); } } else { System.out.println("缺少文件名"); } return md5Content; } } |
上传校验
调用上传检验接口时,点播服务会根据媒资的MD5值来检查是否已有重复的媒资文件。MD5值的生成方式是取媒资文件的1024字节,并进行MD5计算,示例代码如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.SeekableByteChannel; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import org.apache.commons.codec.digest.DigestUtils; public class VodDemoDuplicateCheckMd5 { public static String computeMd5ByFile(String fileUrl) { String md5Content = null; Path targetFile = Paths.get(fileUrl); try (SeekableByteChannel channel = Files.newByteChannel(targetFile, StandardOpenOption.READ)) { ByteBuffer byteBuffer = ByteBuffer.allocate(1025); channel.read(byteBuffer); byteBuffer.flip(); byte[] data = new byte[byteBuffer.limit()]; byteBuffer.get(data); md5Content = DigestUtils.md5Hex(data); } catch (IOException e) { throw new RuntimeException(String.format("Read file %s failed.", fileUrl)); } return md5Content; } } |
父主题: 附录