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

时间:2012-06-08 14:36:42

标签: java hash azure md5 blob

我将一些图片存储在microsoft azure中。上传和下载运行良好。但我想用md5-hash验证上传的数据,独立于上传和下载。所以这是我的代码(整个连接和帐户的工作原理。容器也不是null):

public String getHash(String remoteFolderName, String filePath) {

    CloudBlob blob = container.getBlockBlobReference(remoteFolderName + "/" + filePath);

    return blob.properties.contentMD5
}

问题是,我总是为每个blob获取null。 我是以正确的方式做到这一点还是有其他可能获得blob的md5-hash?

2 个答案:

答案 0 :(得分:2)

只有在您上传blob时设置了MD5哈希才可用。有关详情,请参阅此帖子:http://blogs.msdn.com/b/windowsazurestorage/archive/2011/02/18/windows-azure-blob-md5-overview.aspx

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

答案 1 :(得分:2)

我已经解决了这个问题,就像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')
}