Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS file upload sends stale formData

I use https://github.com/nervgh/angular-file-upload for file uploads.

I have a form which, in addition to uploading a file, sends some other fields. For clarity, I send only one field in this example:

$scope.save_with_upload = function(user) {
    $scope.uploader.formData = [{
        name: user.name,
    }];

    $scope.uploader.uploadAll();
}

Let’s say the value of the name input is Test 1.

  1. When I first load the page and click Save, it sends the file but doesn’t send formData at all.
  2. Then I change name field to Test 2 and hit Save. It sends the file and formData, but the value of name it sends is Test 1.
  3. Then I change name field to Test 3 and hit Save. It sends the file and formData, but the value of name it sends is Test 2.
  4. … and so on …

So it seems to always send the data that was assigned to formData before the last call to uploadAll.

To clarify: If I do dir(user, $scope.uploader.formData) just before calling uploadAll, it shows correct up-to-date values in both.

I’ve been struggling with it for a few hours and just can’t seem to see what’s wrong. Any ideas?

like image 634
Pawel Decowski Avatar asked Aug 27 '14 11:08

Pawel Decowski


1 Answers

Attaching form fields to the FileItem object — rather than to FileUpload — fixes it:

uploader.onBeforeUploadItem = function(item) {
    formData = [{
        name: user.name,
    }];
    Array.prototype.push.apply(item.formData, formData);
};

The reason is, actually the settings on FileItem are used. When a file is added to the queue, settings from FileUpload are copied to FileItem. So any changes to FileUpload options made after a file has been added to the queue will have no effect.

like image 184
Pawel Decowski Avatar answered Sep 28 '22 02:09

Pawel Decowski