Search code examples
javascriptangularfile-uploadng2-file-upload

Angular 2 - upload file in array


im having trouble trying to use an uploader inside an array:

I have an array of user being listed in a table using "ng-repeat". I wanna add a column with a button to upload an image for each of them. Im currently using ng2-file-upload but no problem to change it to other.

<table>
  <thead>
    <th>User Id</th>
    <th>User Name</th>
    <th>View / Upload photo</th>
  </thead>
  <tbody>
    <tr *ngFor="let user of users; let i = index" [attr.data-index]="i">
      <td>{{user.id}}</td>
      <td>{{user.name}}</td>
      <td>
        <div *ngIf="user.photo">
          <a href="{{user.photo}}>View photo</a>
        </div>
        <div *ngIf="!user.photo">
          <input class="btn" type="file" ng2FileSelect [uploader]="uploader"/>
        </div>
      </td>
      <td>
    </tr>
  </tbody>
</table>

In the component, I know I need to declare the uploader with the URL of my api to upload file using the following code:

uploader: FileUploader = new FileUploader({url: URL});
this.uploader.onCompleteItem = (item:any, response:any, status:any, headers:any) => {
  this.photo = JSON.parse(response).path;
};

However this code wont work for each user.

Problem is that i cant find the way to get the uploaded filepath from each user to save it in a variable that would let me save it to database.

I know there is a function to get the file name but I am having trouble getting the value for each user's photo.

Does anyone of you done such a thing? Maybe you can show me the way I can get it working.

I guess i have to create the uploader dynamically for each user, so each uploader have their own filepath but how can i get it done? Or maybe its ok to have only one uploader but I need to get the user id when i am inside the onCompleteItem function so I can save the filepath to the current user in database?

Thanks for your guidance.


Solution

  • The only workaround I can think of here is if you would listen to the onChange event on the input and pass the associated user:

    <input class="btn" type="file" 
           (change)="selectedUserPhoto($event, user)" 
           ng2FileSelect [uploader]="uploader"/>
    

    Then in the event handler you could save the file name on the user object:

    `user.photoPath = event.target.files[0].name;`
    

    And in the component class you listen on the uploader for onCompleteItem and onErrorItem. In both handlers you will have the name of the file and you can loop through the users to find the right one and either save or discard the changes, depending on the upload result.