Microsoft Azure:如何在 Java 中获取 blob 的 md5-hash



>im 在 Microsoft Azure 中存储一些图片。 上传和下载运行良好。 但我想使用 MD5 哈希验证上传的数据,独立于向上和下载。 所以这是我的代码(整个连接和帐户正常。 容器也不是空):

public String getHash(String remoteFolderName, String filePath) {
    CloudBlob blob = container.getBlockBlobReference(remoteFolderName + "/" + filePath);
    return blob.properties.contentMD5
}

问题是,我总是为每个 blob 获取 null。我是否以正确的方式执行此操作,或者是否有其他可能性来获取 blob 的 MD5 哈希?

我已经解决了这个问题,就像 smarx 对它进行的那样。在上传之前,我计算了文件的 md5-Hash 并在 blob 的属性中更新它:

import java.security.MessageDigest
import com.microsoft.windowsazure.services.core.storage.utils.Base64;
import com.google.common.io.Files
String putFile(String remoteFolder, String filePath){
    File fileReference = new File (filePath)
    // the user is already authentificated and the container is not null
    CloudBlockBlob blob = container.getBlockBlobReference(remoteFolderName+"/"+filePath);
    FileInputStream fis = new FileInputStream(fileReference)
    if(blob){
        BlobProperties props = blob.getProperties()
        MessageDigest md5digest = MessageDigest.getInstance("MD5")
        String md5 = Base64.encode(Files.getDigest(fileReference, md5digest))
        props.setContentMD5(md5)
        blob.setProperties(props)
        blob.upload(fis, fileReference.length())
        return fileReference.getName()
   }else{
        //ErrorHandling
        return ""
   }
}

上传文件后,我可以使用此方法获取 ContentMD5:

String getHash(String remoteFolderName, String filePath) {
    String fileName = new File(filePath).getName()
    CloudBlockBlob blob = container.getBlockBlobReference(remoteFolderName+"/"+filePath)
    if(!blob) return ""
    blob.downloadAttributes()
    byte[] hash = Base64.decode(blob.getProperties().getContentMD5())
    BigInteger bigInt = new BigInteger(1, hash)
    return bigInt.toString(16).padLeft(32, '0')
} 

MD5 哈希仅在上传 Blob 时设置时才可用。有关更多详细信息,请参阅此帖子:http://blogs.msdn.com/b/windowsazurestorage/archive/2011/02/18/windows-azure-blob-md5-overview.aspx

是否有可能从未为这些 blob 设置 MD5 哈希?

最新更新