我想从我的笔记本电脑BLOB(PDF)文件上传到Azure存储帐户的容器。 我发现它是工作,但有一个小故障。
我计算使用的文件大小:
f_info = os.stat(file_path)
file_size = (f_info.st_size) # returns - 19337
然后我插入下面规范化头这个值:
ch = "PUT\n\n\n"+str(file_size)+"\n\napplication/pdf\n\n\n\n\n\n\nx-ms-blob-type:BlockBlob" + "\nx-ms-date:" + date + "\nx-ms-version:" + version + "\n"
和发送PUT请求把一滴API,但是,它返回一个错误的说法,“验证失败,因为下面的字符串下面使用的服务器计算签名”
\'PUT \ n \ n \ n 19497 \ n \ napplication / PDF \ n \ n \ n \ n \ n \ n \ NX-MS-团块型:BlockBlob \ NX-MS-日期:[日期] \ NX -MS-版本:[API版本]
望着这串显然表明身份验证失败,因为其Azure的计算文件大小返回不同的值! 我不明白它是如何计算文件大小的这个值?!?!
FYI:如果我在规范化字符串替换19497 19337并重新运行。 有用! 在这里我犯错误任何建议?
下面是代码:
storage_AccountName = '<storage account name>'
storage_ContainerName = "<container_name>"
storageKey='<key>'
fd = "C:\\<path>\\<to>\\<file_to_upload>.pdf"
URI = 'https://' + storageAccountName + '.blob.core.windows.net/<storage_ContainerName >/<blob_file_name.pdf>
version = '2017-07-29'
date = datetime.datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S GMT")
if os.path.isfile(fd):
file_info = os.stat(fd)
file_size = (file_info.st_size)
ch = "PUT\n\n\n"+str(file_size)+"\n\napplication/pdf\n\n\n\n\n\n\nx-ms-blob-type:BlockBlob" + "\nx-ms-date:" + date + "\nx-ms-version:" + version + "\n"
cr = "/<storage_AccountName>/<storage_Containername>/<blob_file_name.pdf>"
canonicalizedString = ch + cr
storage_account_key = base64.b64decode(storageKey)
byte_canonicalizedString=canonicalizedString.encode('utf-8')
signature = base64.b64encode(hmac.new(key=storage_account_key, msg=byte_canonicalizedString, digestmod=hashlib.sha256).digest())
header = {
'x-ms-blob-type': "BlockBlob",
'x-ms-date': date,
'x-ms-version': version,
'Authorization': 'SharedKey ' + storageAccountName + ':' + signature.decode('utf-8'),
#'Content-Length': str(19497), # works
'Content-Length': str(file_size), # doesn't work
'Content-Type': "application/pdf"}
files = {'file': open(fd, 'rb')}
result = requests.put(url = URI, headers = header, files = files)
print (result.content)