Search code examples
javascriptangulartypescriptng2-file-upload

How to appropriately change the filename for ng2-file-uploader in angular


I want to change the name of my image in angular via the ng2-file-uploader and then pass it to my multer in my node.js.

Everything is working fine. I am able to receive the image and it is being stored in my upload directory on server side. It is just that I don't know where to change the image name. I tried it in the onCompleteItem method but nothing. Here is some code:

import {  FileUploader, FileSelectDirective } from 'ng2-file-upload/ng2-file-upload';

@Component({
  selector: 'name',
  templateUrl: './some.html',
  styleUrls: [./some.css]
})
export class ComponentName {
  public uploader: FileUploader = new FileUploader({ url: "myurl", itemAlias: 'myPhoto' });

  ngOnInit(){
    this.uploader.onAfterAddingFile = (file) => {};
    this.uploader.onCompleteItem = (item: any, response: any, status: any, headers: any) => {
      //create my name
      item.file.name = "my name"
      alert('File uploaded');
    }; 
    this.uploader.uploadAll();
  }
}

I just want to change the name so that I can store it in my database together with the other input values that I have.


Solution

  • This is actually quite simple. You almost got it, but you chose the wrong method. You can change the file name in the onAfterAddingFile method. Below I can show you some code

    import {  FileUploader, FileSelectDirective } from 'ng2-file-upload/ng2-file-upload';
    
    @Component({
      selector: 'name',
      templateUrl: './some.html',
      styleUrls: [./some.css]
    })
    export class ComponentName {
      public uploader: FileUploader = new FileUploader({ url: "myurl", itemAlias: 'myPhoto' });
    
      //new name string variable
      newFileName : string;
    
      ngOnInit(){
        this.uploader.onAfterAddingFile = (file) => {
          //create my name
          file.file.name = "new name";
          //save in variable
          newFileName = file.file.name;
        };
        this.uploader.onCompleteItem = (item: any, response: any, status: any, headers: any) => {
          alert('File uploaded');
        }; 
        this.uploader.uploadAll();
      }
    }
    

    That way you can pass a complete new file name or you could use javascript's string replace method and regex to replace characters in your file name. Hope this helped.