问题描述
我正在使用 https://zatackcoder.com/upload-file-to-google-cloud-storage-using-php/ 中的代码示例将文件上传到 Google Cloud。一切正常(我是新手,所以我很高兴让它运行!),但我最近读了一篇简介,你可以告诉谷歌云你上传的文件的 md5 是什么,谷歌会验证与实际上传不符,如果传输问题导致 md5 不同,则上传失败。
我的问题分为两部分:
-
如何以 Google Cloud 能够理解的格式计算 md5?我相信计算实际上是从 PHP 的 file_md5() 返回的 md5 的 base64_encode() 但是当我这样做时,结果字符串实际上与从 Google 返回的结果 "md5Hash": "TPmaCjp5uh1jxIQahhOAsQ==" 有很大不同.我正在使用 Google Cloud STORAGE API 执行上传(请参阅上面的链接和下面的次要代码段)。
-
一旦我正确计算了 md5Hash,我该如何在 upload() 函数中指定该值以将该值作为上传的一部分传递?有没有人做过这个并且可以分享他们的专业知识?
非常感谢!
这是上面链接中较大项目的片段。上传工作正常,我只是在寻找如何生成适当的 md5Hash 并将该哈希包含在上传中。
function uploadFile($bucketName,$fileContent,$cloudpath) {
$privateKeyFileContent = $GLOBALS['privateKeyFileContent'];
// connect to Google Cloud Storage using private key as authentication
try {
$storage = new StorageClient([
'keyFile' => json_decode($privateKeyFileContent,true)
]);
} catch (Exception $e) {
// maybe invalid private key ?
print $e;
return false;
}
// set which bucket to work in
$bucket = $storage->bucket($bucketName);
// upload/replace file
$storageObject = $bucket->upload(
$fileContent,['name' => $cloudpath]
// if $cloudpath is existed then will be overwrite without confirmation
// NOTE:
// a. do not put prefix '/','/' is a separate folder name !!
// b. private key MUST have 'storage.objects.delete' permission if want to replace file !
);
// is it succeed ?
return $storageObject != null;
}
解决方法
根据PHP client library for Cloud Storage documentation,您可以在StorageObject
对象的upload
method 中指定一个metadata
参数。
这个参数是一个数组,允许你传递 md5Hash。您可以传递的属性的完整列表在 here 中说明。