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

时间:2017-09-09 11:58:42

标签: azure cors azure-storage azure-storage-blobs azure-blob-storage

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

  

阻止跨源请求:同源策略禁止读取   远程资源at(Reason:CORS header   “Access-Control-Allow-Origin”缺失。)

我读到了有关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网址,它将获得此SAS网址,之后我们需要选择文件并上传。 谁能告诉我究竟是什么问题? 感谢

1 个答案:

答案 0 :(得分:1)

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

enter image description here

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

enter image description here