How to handle file upload errors using angularjs?

Uploading files looks very trivial, and there are many working solutions. Work until the server reports 401 UNAUTHORIZED. My requirements are pretty natural:

  • In no case can the current window be replaced.
  • I do not want to open a new window, as this does not make sense.
  • If an error occurs, the user should be shown a message.

I tried to use iframelinks as a target and hoped that you would be notified in case of an error. I see that I am naive.

  • I could imagine to place in> a script that would notify the main page onunload. It looks a little more complicated, so I ask first.
  • I could ask the server about the totals. That will surely work. But this is also difficult, since the synchronization problem and the session has expired, so I would have to work around this.
+5
source share
2 answers

You can use an object to start a file download with javascript. This is being entered from the API files and is still in the working draft. This way you will have limited browser support. Since 2015 you have the broad support for the browser URL-addresses Blob and blocks constructor . Blob

<div ng-controller="appController" ng-app="app">
    <a ng-href="{{ fileUrl }}" download="file.txt">download</a>
</div>
var app = angular.module('app', []);

// Angular prepends "unsafe" tag in ng-href to prevent XSS
// so we need to sanitize this
app.config(['$compileProvider', function ($compileProvider) {
    // for Angular 1.0.x and 1.1.x, you should use urlSanitizationWhitelist
    $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|blob|ftp):/);
}]);

app.controller('appController', function ($scope, $window) {
    // Creating a Blob with our data for download
    // this will parse the URL in ng-href such as: blob:http...
    var data = 'some data here...',
        blob = new Blob([data], { type: 'text/plain' }),
        url = $window.URL || $window.webkitURL;
    $scope.fileUrl = url.createObjectURL(blob);
});

See the demo script here .

, Blob.js

FileSaver.js, data:URI.

+7

HTTP-, /, HTTP-. , , , .

$httpProvider.interceptors.push(function($q, dependency1, dependency2) {
    return {
       'request': function(config) {
        // same as above
        },

        'response': function(response) {
        // same as above
     }
  };

});

-1

All Articles