6

I work on an angular front-end based on a fake backend implementation for development.

This fake storage is built using localStorage and the http request are handled by the e2e $httpBackend. All of this works nicely until i tried to fake a file upload service.

In my client code i have the following service (based on this post):

angular.module('myApp')
    .service('fileUpload', ['$http', function ($http) {
    this.uploadFileToUrl = function(file, uploadUrl) {
        var fd = new FormData();
        fd.append('file', file);
        $http.post(uploadUrl, fd, {
          transformRequest: angular.identity,
          headers: {'Content-Type': undefined}
        });
    };
}]);

and the fake upload service:

angular.module('myApp')
  .run(function($httpBackend, $log) {
    $httpBackend.whenPOST('api/upload').respond(function(method, url, data) {
      // data is a FormData
      // TODO
      // read the content
      // store to local storage
      return [200, 'uploaded/path'];
    });

  });

The receive data is a FormData. All i read around about FormData is that it is a write only object.

how can i read the file content to store it into the local storage ?

gontard
  • 28,720
  • 11
  • 94
  • 117
  • i'd like to see an answer to this as well – Robert Johnstone May 29 '15 at 09:05
  • 1
    @Sevenearths you might offer a bounty ;) – gontard May 29 '15 at 13:05
  • I found what I was looking for here > http://stackoverflow.com/questions/2198470/javascript-uploading-a-file-without-a-file – Robert Johnstone May 29 '15 at 14:52
  • Unfortunately after the `$http.post` the request would be converted by XHR as a raw text request with multi-part form data with data being enclosed in the multipart start and end boundry. If you are interested in other solutions you will have to spell exactly what you intend to validate in your e2e test to narrow down the solutions. Are you trying to validate the contents of the uploaded file ? – bhantol Jan 22 '18 at 23:08
  • You could inject your $httpProvider.interceptors and catch the inflight request or perhaps even cancel it faking that it went successfully or use your local storage to capture the request. – bhantol Jan 22 '18 at 23:16

0 Answers0