Azure PageBlob上传新文件:x-ms-blob-content-length错误



我想写一个简单的python代码来上传一个文件到Azure PageBlob。我不确定我应该为x-ms-blob-content-length指定什么,因为我一直得到错误。文档不是很清楚。

我的代码试图用0左垫文件,以确保其在512字节边界内,但我不知道我是否在正确的路径上。谢谢你。

import sys
import os
import http.client
from urllib.parse import urlparse
sas_uri = '<SAS URI here>'
uri = urlparse(sas_uri)
conn = http.client.HTTPSConnection(uri.hostname, port=uri.port, timeout=3000)
file_path = r"C:UsersuserDownloadsnpp.Installer.exe"
with open(file_path, 'rb') as reader:
file = reader.read()
size = os.stat(file_path).st_size
boundary = size % 512
if boundary != 0:
file = file.ljust(boundary, b'')
size = size + boundary
headers = {
'Content-Type': 'application/octet-stream',
'Content-Length': 0,
'x-ms-blob-type': 'PageBlob',
'x-ms-blob-content-length': size
}
conn.request('PUT', sas_uri, file, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))

错误:

Connected to pydev debugger (build 211.7142.13)
<?xml version="1.0" encoding="utf-8"?>
<Error><Code>InvalidHeaderValue</Code><Message>The value for one of the HTTP headers is not in the correct format.
RequestId:44c84519-501c-0004-5ecc-937c22000000
Time:2021-08-18T00:57:43.5973565Z</Message><HeaderName>x-ms-blob-content-length</HeaderName><HeaderValue>3991344</HeaderValue></Error>

本质上,问题在于下面这行代码:

size = size + boundary

如果你把这个数除以512,你会注意到这个数不能被512整除。

为了将页面blob的内容长度设置为512的倍数,您需要使用以下逻辑:

size = size + 512 - boundary

请试一试。应该可以。

最新更新