我已经为此苦苦挣扎了大约一天。我正在直接测试 Azure Blob 存储上传并遇到可怕的 CORS 问题。 “XMLHttpRequest无法加载https://tempodevelop.blob.core.windows.net/tmp/a4d8e867-f13e-343f-c6d3-a603…Ym0PlrBn%2BU/UzUs7QUhQw%3D&sv=2014-02-14&se=2016-10 -12T17%3A59%3A26.638531。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin” header 。来源“http://localhost:8000”是因此不允许访问。响应的 HTTP 状态代码为 403。”
我已经尝试过的事情:
- 将 CORS 设置为所有主机:
- 尝试在本地和 Heroku 上托管我的应用
- 确保我可以使用其他工具(Azure 存储资源管理器)上传文件
- 将我的 AccessPolicy 配置为“rwdl”,我肯定会获得访问签名(在单元测试中验证)。
整个代码可以在这里找到:https://github.com/mikebz/azureupload
但是相关部分在这里,前端上传:
<script>
/*
* not a true GUID, see here: http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript
*/
function guid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
}
function startUpload() {
var fileName = guid();
jQuery.getJSON("/formfileupload/signature/" + fileName , function(data) {
console.log("got a signature: " + data.bloburl);
uploadFile(data.bloburl, data.signature);
})
.fail(function(jqxhr, textStatus, error) {
console.log( "error: " + textStatus + " - " + error );
})
}
function uploadFile(bloburl, signature) {
var xhr = new XMLHttpRequest();
fileData = document.getElementById('fileToUpload').files[0];
xhr.open("PUT", bloburl + "?" + signature);
xhr.setRequestHeader('x-ms-blob-type', 'BlockBlob');
xhr.setRequestHeader('x-ms-blob-content-type', fileData.type);
result = xhr.send(fileData);
}
</script>
Python中的签名生成代码在这里:
def generate_access_signature(self, filename):
"""
calls the Azure Web service to generate a temporary access signature.
"""
blob_service = BlobService(
account_name=self.account_name,
account_key=self.account_key
)
expire_at = datetime.utcnow()
expire_at = expire_at + timedelta(seconds = 30)
access_policy = AccessPolicy(permission="rwdl", expiry=expire_at.isoformat())
sas_token = blob_service.generate_shared_access_signature(
container_name="tmp",
blob_name = filename,
shared_access_policy=SharedAccessPolicy(access_policy)
)
return sas_token
最佳答案
根据错误消息[响应的 HTTP 状态代码为 403],可能是服务未启用 CORS,或者没有与预检请求匹配的 CORS 规则。详情请引用Cross-Origin Resource Sharing (CORS) Support for the Azure Storage Services 。 或者可能是 SAS 签名不正确。 请尝试排除故障
还有Azure explore可用于生成 SAS token 的工具
关于azure - 上传到 Azure Blob 时请求的资源上不存在 'Access-Control-Allow-Origin' header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40005725/