Reputation: 147
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.
Upvotes: 0
Views: 1956
Reputation: 12794
You can use onAfterAddingAll
as workaround:
this.uploader.onAfterAddingAll = (files: FileItem[]) => {
files.forEach(fileItem => {
fileItem.file.name = fileItem.file.name.replace(/\.[^/.]+$/, "");
(<any>fileItem).previewUrl = this.sanitizer.bypassSecurityTrustUrl((window.URL.createObjectURL(fileItem._file)));
});
};
Upvotes: 1
Reputation: 597
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.
Upvotes: 2