简体   繁体   中英

Angular 7 - Upload file to server

I´m trying to send input file to server. When input file has data return in console this

 FileList {0: File, length: 1}0: File {name: "8mn4p369li331.png", lastModified: 1567609045831, lastModifiedDate: Wed Sep 04 2019 16:57:25 GMT+0200 (hora de verano de Europa central), webkitRelativePath: "", size: 9587062, …}length: 1__proto__: FileList

I try to put this in formData element like this but doesn´t work

  save(form: NgForm) {
       const formData: FormData = new FormData();
       formData.append('file', this.selectedFiles, this.fileName)
       form.value["file"] = formData;
}

So: What´s is the right way to upload file (in a form) to the server?

UPDATE: onChange function

  fileEvent(event:any){
    this.selectedFiles = event.target.files;
    this.fileName = this.selectedFiles[0].name;
    console.log(this.selectedFiles);

}

Provided you have the right file:

let formdata = new FormData();
formdata.set('file', file, "fileName");

I believe you can only set one file per variable...

Edit: My file variable is a Blob...

Blob {size: 3151, type: "application/pdf"}

your save function should be

save(form: NgForm) {
   const formData: FormData = new FormData();
   formData.append('file', this.selectedFiles[0], this.fileName)
   form.value["file"] = formData;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM