微软Azure:如何在Java中获取blob的md5哈希值

4

我将一些图片存储在Microsoft Azure中。上传和下载功能正常,但我希望独立于上传和下载的情况下使用MD5哈希验证已上传的数据。因此,这是我的代码(整个连接和帐户事务都可以运作,容器也不为空):

public String getHash(String remoteFolderName, String filePath) {

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

    return blob.properties.contentMD5
}

问题是,我每次都得到空的blob。我这样做对吗?还是有其他方法可以获取blob的md5哈希值?

2
如果在访问属性之前调用 blob.FetchAttributes() 会发生什么? - sharptooth
我认为你的意思是blob.downloadAttributes(),因为我找不到叫做FetchAttributes()的方法。实际上,我也尝试过这个方法,但结果是一样的。附注:我正在使用microsoft-windowsazure-api-0.2.2.jar,并且我有一个Azure的学生账户。 - DiKorsch
我从未见过Azure SDK的Java API,我猜它确实可能有不同的名称,但这会很奇怪。 - sharptooth
我从这里得到了它:https://github.com/WindowsAzure/azure-sdk-for-java - DiKorsch
稍微有些不相关,但.NET SDK也存在这个问题。引用CloudBlockBlob.Properties.ContentMD5属性会返回null,除非在blob引用对象上调用了FetchAttributes()。解释在这里:https://dev59.com/SGkw5IYBdhLWcg3wSovA - varun
2个回答

4

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

现在对于小文件来说通常是“自动设置”的,但对于大文件来说则不是,因此手动设置可能是最安全的方式。https://dev59.com/_5_ha4cB1Zd3GeqPuCIA#69319211 - rogerdpack

2

我猜这应该是问题所在。我只是上传文件而没有设置ContentMD5属性。我会尝试在上传之前设置这个值,并尽快在这里发布结果。 - DiKorsch
自2012年以来,对于小的blob,它被“自动”设置。FWIW https://dev59.com/_5_ha4cB1Zd3GeqPuCIA#69319211 - rogerdpack

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接