Search code examples
javascriptangularjscross-domainng-file-upload

ng-file-upload cross domain error


I am able to post a base 64 encoded image via postman and even via my app when i use simple javascript request like this:

var data=       "userPhoto=data%3Aimage%2Fjpeg%3Bbase64%2C%2F9j%2F4AAQSkZJRgABAQEAS ................(image data) Rd1bbfc2B%2FdDXGWxWHtA2N6NrL%2BLNf6wIa92a5m5v2s0c7tObhgdJMdV6Rm4mt7YkqukTMsv2vVsgl5j73tQasFOHYMP3nqf%2F%2FZ";
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
  console.log(this.responseText);
 }
});

xhr.open("POST", "http://localhost:8000/test2");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("postman-token", "b98cbdf1-8918-b8fb-6b50- a626c301cffc");
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xhr.send(data);

But when i use the simple code copied from ng-file-upload

HTML:

  <div class="button" ngf-select ng-model="file" name="file" ngf-pattern="'image/*'" ngf-accept="'image/*'" ngf-max-size="20MB" ngf-min-height="100" ngf-resize="{width: 100, height: 100}">Select</div>

Script:

var app = angular.module('fileUpload', ['ngFileUpload']);
app.controller('MyCtrl', ['$scope', 'Upload', function ($scope, Upload) {
// upload later on form submit or something similar
$scope.submit = function() {
  if ($scope.form.file.$valid && $scope.file) {
    $scope.upload($scope.file);
  }
}; 

I get a cross domain error:

XMLHttpRequest cannot load 'url'. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

Basically I have tried all different combinations starting from actual scenario to simplified version to the most basic use case on the site. Its just me or angular errors are really frustrating because of so many layers in between. C# was definitely not so hard


Solution

  • Okay figured it out. In the upload function i was using the entire URL http://localhost:8000/test1, but I was supposed to use just /test1

    $scope.upload = function (file) {
        Upload.upload({
            url: '/test1',
            data: {'userPhoto':file}
        }).then(function (resp) {
            console.log('Success ' + resp.config.data.file.name + 'uploaded.    Response: ' + resp.data);
        }, function (resp) {
            console.log('Error status: ' + resp.status);
        });
    };