1
votes

I am working with azure blob storage, i have done that with PHP language, now i want to upload files on azure blob storage with jquery, so i used one plugin for that, when i try to upload file on that it is giving me error in console

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

I read about the CORS configuration, and i enable that configuration in Azure Blob Storage, here is my screenshot for that

Azure Blob CORS Info Image

Here is my jquery code

$(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 () { });
    }

In the input we need to add "Input Your Container SAS Here" i am adding there 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‌​=****** this SAS url, it will get this SAS url and after then we need to select file and upload it. Can anyone please tell me what is exact issue ? Thanks

1
Please change the exposed headers to * (like allowed headers). Any mismatch in allowed origins, verbs, allowed and exposed headers will cause this issue you're facing.Gaurav Mantri
I did that, i am still getting same errorNikul Panchal
Please include this and your code in your question itself and not in comments.Gaurav Mantri
Please STOP providing these details in comments. Add all the relevant information in the question itself. You must have written some code (some HTML page, some JS code, something) that consumes this library. Please include that in the question as well.Gaurav Mantri
So I got an opportunity to download the code from the Github repo and ran the demo. I was able to successfully upload a file from my local computer (it was a very small file though). So the code works just fine. I suggest you start by checking CORS rules and the Shared Access Signature. You may want to write some code (not HTML/JS...probably C#) and try to upload a blob using SAS using that code.Gaurav Mantri

1 Answers

1
votes

I also download and test the library, it worked fine with following setting on my blob storage service. The MaxAgeInSeconds setting will cache the preflight OPTIONS request. I suggest you reset it to 0 and run your code again(Please use different browsers to test it).

enter image description here

In addition, there are multi CORS setting under Azure Storage panel. Please mark sure that you were setting the right one for Azure Blob Storage.

enter image description here