【问题标题】:Microsoft Azure: how get md5-hash of a blob in JavaMicrosoft Azure:如何在 Java 中获取 blob 的 md5-hash
【发布时间】:2012-06-12 15:15:30
【问题描述】:

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

public String getHash(String remoteFolderName, String filePath) {

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

    return blob.properties.contentMD5
}

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

【问题讨论】:

  • 如果在访问属性之前调用blob.FetchAttributes() 会发生什么?
  • 我认为您的意思是 blob.downloadAttributes(),因为我找不到名为 FetchAttributes() 的方法。确实,我也试过这个,但结果是一样的。 p.s.:我正在使用 microsoft-windowsazure-api-0.2.2.jar,并且我有一个 azure 的学生帐户
  • 我没见过Azure SDK的Java API,我猜它确实可能有不同的名字,但它会很奇怪。
  • 有点不相关,但是.NET SDK也有这个问题。除非在 blob 引用对象上调用了 FetchAttributes(),否则引用 CloudBlockBlob.Properties.ContentMD5 属性将返回 null。此处说明:stackoverflow.com/questions/9994777/…

标签: java hash azure md5 blob


【解决方案1】:

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

【讨论】:

【解决方案2】:

只有在您上传 blob 时设置了 MD5 哈希值,它才可用。更多详情请看这篇文章:http://blogs.msdn.com/b/windowsazurestorage/archive/2011/02/18/windows-azure-blob-md5-overview.aspx

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

【讨论】:

  • 我想这一定是问题所在。我只是上传文件而不设置 ContentMD5 属性。我会在上传之前尝试设置这个值,并尽快在此处发布结果
  • 自 2012 年以来,它被设置为“自动”用于小 blob FWIW stackoverflow.com/a/69319211/32453
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-10
  • 2022-11-06
  • 2012-05-02
  • 2021-09-05
  • 2021-08-30
  • 1970-01-01
  • 2019-03-22
相关资源
最近更新 更多