azure - 在 azure blob 存储上上传文件时出现问题

标签 azure cors azure-storage azure-blob-storage

我正在使用azure blob存储,我已经用PHP语言完成了这一点,现在我想使用jquery将文件上传到azure blob存储上,所以我使用了一个插件,当我尝试上传文件时,它是在控制台中给我错误

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

我了解了 CORS 配置,并在 Azure Blob 存储中启用了该配置,这是我的屏幕截图

Azure Blob CORS Info Image

这是我的 jquery 代码

$(function () {
        var ju = {
            sasUrl: $('#txtSAS'),
            list: $('#tbFileList tbody'),
            btnUpload: $('#btnUpload'),
            btnClear: $('#btnClear'),
            btnAddFile: $('#btnAddFile'),
            sasSearchName: 'sas',
            btnLink: $('#btnLink'),
            linkPopover: $('#linkPopover'),
            init: function () {
                this.root = location.href;
                if (this.root.indexOf('?') > 0) {
                    this.root = this.root.substr(0, this.root.indexOf('?'));
                    this.root = this.root.replace(/#/g, '');
                }
                this.btnClear.hide();
                var sas = this.queryString(this.sasSearchName);
                if (sas) {
                    this.sasUrl.val(sas);
                }
                this.list.blobuploader(
                {
                    url: ju.sasUrl.val(),
                    beforeSend: function (blob) {
                    },
                    progress: function (blob) {
                        ju.progress(blob.element.closest('tr'), blob.loaded, blob.size);
                    },
                    success: function (blob, data, status) {
                        var st = blob.speed(true);
                        var msg = 'total time: ' + ((st.end - st.start) / 1000).toFixed(2) + 'S<br/>'
                            + 'max speed: ' + st.max + '<br/>'
                            + 'min speed: ' + st.min + '<br/>'
                            + 'average speed: ' + st.average;
                        ju.status(blob.element, msg);
                        var download = '<a target="_blank" role="button" class="btn btn-link" href="'
                            + blob.blobUrl
                            + '" >' + blob.name + '</a>';
                        ju.log(blob.element.closest('tr').find('td:first'), download);
                    },
                    error: function (blob, block, xhr, desc, err) {
                        var msg = $('<span></span>');
                        msg.append('upload ' + blob.name + ' error.');
                        var btn = $('<button type="button" id="btnUpload" class="btn btn-sm btn-primary pull-right" role="button">Retry</button>');
                        btn.click(function () {
                            ju.retry($(this).closest('tr'));
                        });
                        msg.append(btn)
                        ju.status(blob.element, msg, 'danger');
                    }
                });
                this.btnClear.click(function () {
                    ju.clear();
                });
                this.btnAddFile.find('input').on('change', function () {
                    ju.add();
                });
                this.btnUpload.click(function () {
                    ju.upload();
                });
                this.btnLink.popover({
                    html: true,
                    content: this.linkPopover,
                    container: 'body'
                });
                this.btnLink.on('shown.bs.popover', function () {
                    var panel = $('#linkPopover');
                    panel.find('#txtShareUrl').val(ju.getLongUrl());
                    panel.find('#ckShortUrl').click(function () {
                        if ($(this).is(':checked')) {
                            ju.generateShortUrl();
                        } else {
                            panel.find('#txtShareUrl').val(ju.getLongUrl());
                        }
                    })
                    panel.find('.close').click(function () {
                        ju.btnLink.popover('toggle');
                    });
                    panel.find('#ckShortUrl').attr('checked', false);
                    panel.find('.loading').hide();
                });
                this.sasUrl.on('change', function () {
                    ju.linkPopover.find('#ckShortUrl').attr('ckecked', false);
                    ju.linkPopover.find('.loading').hide();
                });
                var code = $('.prettyprint');
                code.text(code.text().replace('site-domain', location.origin));
            },
            progress: function (tr, loaded, total) {
                var percent = (loaded / total * 100).toFixed(2);
                var span = tr.find('td:last .percent');
                if (span.length == 0) {
                    span = $('<span class="percent"/>').appendTo(tr.find('td:last').empty());
                }
                span.text(percent + '%');
            },
            log: function (td, message, type) {
                var div = td.empty();
                if (type) {
                    div = $('<div class="alert alert-' + type + '"/>').appendTo(td);
                }
                if (message instanceof jQuery) {
                    div.append(message);
                } else {
                    div.html(message);
                }
            },
            information: function (element, info, type) {
                var td = element.closest('tr').find('td:eq(1)');
                if (info) {
                    ju.log(td, info, type);
                } else {
                    return td.html();
                }
            },
            status: function (element, message, type) {
                var td = element.closest('tr').find('td:last');
                if (message) {
                    ju.log(td, message, type);
                } else {
                    return td.html();
                }
            },
            add: function () {
                var tr = $('<tr/>'), td = $('<td/>');
                var file = this.btnAddFile.find('input');
                this.btnAddFile.append(file.clone(true));
                var f = file.get(0).files[0];
                td.append(file)
                    .append(f.name)
                    .appendTo(tr);
                td = $('<td/>')
                    .append(f.type, f.type ? '<br/>' : '', (f.size / 1000).toFixed(2) + 'KB')
                    .appendTo(tr);
                $('<td><span class="percent"></span></td>').appendTo(tr);
                tr.appendTo(this.list);
                this.btnClear.show();
            },
            setProperties: function () {
                if (!this.sasUrl.val()) {
                    alert('Please typedin the Container SAS');
                    return;
                }
                var blockSize = parseInt($('#txtBlockSize').val());
                var maxThread = parseInt($('#txtMaxThread').val());
                if (isNaN(blockSize) || isNaN(maxThread)) {
                    alert("Block Size and Max Thread can only be number.");
                    return;
                }
                if (blockSize > 4096) {
                    alert('The block size should be less than 4096kb');
                    return;
                }
                if (blockSize < 1) {
                    alert('The block size should be greater than 1kb');
                    return;
                }
                if (maxThread < 0) {
                    maxThread = 0;
                }
                this.list.blobuploader('option', { maxThread: maxThread, blockSizeKB: blockSize, url: this.sasUrl.val() });
                return true;
            },
            upload: function () {
                if (this.setProperties()) {
                    this.list.blobuploader('upload');
                }
            },
            retry: function (tr) {
                if (this.setProperties()) {
                    if (tr) {
                        var element = tr.find('input[type="file"]');
                        var blob = this.list.blobuploader('blob', element);
                        this.list.blobuploader('retry', blob);
                    } else {
                        this.list.blobuploader('retry');
                    }
                }
            },
            clear: function () {
                this.list.empty();
                this.btnClear.hide();
            },
            queryString: function (name, value) {
                if (!value) {
                    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
                    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
                        results = regex.exec(location.search);
                    return results == null ? "" : atob(decodeURIComponent(results[1].replace(/\+/g, " ")));
                } else {
                    return name + '=' + encodeURIComponent(btoa(value));
                }
            },
            getLongUrl: function () {
                return this.root + '?' + this.queryString('sas', this.sasUrl.val());
            },
            generateShortUrl: function () {
                var request = gapi.client.urlshortener.url.insert({
                    'resource': {
                        'longUrl': this.getLongUrl()
                    }
                });
                request.execute(function (response) {
                    if (response.id != null) {
                        ju.linkPopover.find('.loading').hide();
                        ju.linkPopover.find('#txtShareUrl').val(response.id);
                    }
                    else {
                        ju.linkPopover.find('.loading').text('error.');
                    }
                });
            }
        }
        ju.init();
        prettyPrint();
    })
    function gapiload() {
        gapi.client.setApiKey('AIzaSyDzeVB4WDi6azVvIu6uc8hIhWxf99dB6c8');
        gapi.client.load('urlshortener', 'v1', function () { });
    }

在输入中,我们需要添加“在此处输入您的容器 SAS”,我将在那里添加 https://*****.blob.core.windows.net/?sv=2017-04-17&ss=bfqt&s‌​rt=sco&sp=rwdlacup&s‌​e=2017-09-10T01:51:2‌​ 0Z&st=2017-09-09T17:‌​51:20Z&spr=https&sig‌​=****** 这个 SAS url,它将获取这个 SAS url,然后我们需要选择文件并上传。 谁能告诉我确切的问题是什么? 谢谢

最佳答案

我还下载并测试了该库,它在我的 blob 存储服务上的以下设置中运行良好。 MaxAgeInSeconds 设置将缓存预检 OPTIONS 请求。建议您将其重置为0并再次运行代码(请使用不同的浏览器进行测试)。

enter image description here

此外,Azure存储面板下还有多CORS设置。请确保您为 Azure Blob 存储设置了正确的设置。

enter image description here

关于azure - 在 azure blob 存储上上传文件时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46130425/

相关文章:

sql - Azure SQL 查询突然触发数千次

asp.net - Azure 获取 API 响应时间

cors - 放大 : CORS header ‘Access-Control-Allow-Origin’ missing error even though CORS is enabled in API Gateway and Lambda headers

javascript - 我在 Angular 5 应用程序中遇到 CORS 问题,即使我从服务器得到响应

azure - Azure blob/文件共享存储 NFS 协议(protocol)是否支持 Windows 计算机安装?

azure - 使用 REST API 向 Azure 服务总线队列或主题发送消息

Azure 数据工厂管道

web-services - 如何在 Tomcat Web 服务器版本 6 上启用 CORS

azure - ASP.NET Core Azure WebJob 未记录到 Azure 存储

reactjs - SharedKeyCredential 不是构造函数。 Azure存储 react 应用程序