Upload image without page load

Asked

Viewed 100 times

2

Good evening, I’m uploading file, it’s working but every time I send the file to page updates, could someone give a tip on how to fix it? I’m using angular 5.

Component.

OnSubmit(){

    const formData = new FormData();
    const files: Array<File> = this.filesToUpload;
    for(let i =0; i < files.length; i++){
      formData.append("files[]", files[i], files[i]['name']);
      formData.append('title' ,  this.form.get('title').value);
  }


   this.imageService.postFile(formData).subscribe(data=>{
    // Check if comment was saved to database or not
    if (!data.success) {
      this.messageClass = 'alert alert-danger'; // Return error class
       this.message = data.message; // Return error message
       toast("Erro ao salvar", 4000);
     } else {
      this.messageClass = 'alert alert-success'; // Return success class
       this.message = data.message; // Return success message
       toast("Comentário criado!", 2000);

       setTimeout(() => {

            this.form.reset(); // Reset all form fields

          }, 1000);
       // Clear form data after two seconds

     }
   });
 }
 fileChangeEvent(fileInput: any) {
  this.filesToUpload = <Array<File>>fileInput.target.files;

 // Show image preview
  var reader = new FileReader();
  reader.onload = (event:any) => {
    this.imageUrl = event.target['result'];
  }
  reader.readAsDataURL(fileInput.target.files[0]);
  console.log(fileInput)
}

Component.html

<form [formGroup]="form" (ngSubmit)="OnSubmit()">
    <div class="form-group col-md-4">
      <label for="title">Title :</label>
      <input id="title" placeholder="Title" formControlName="title">
    </div>
      <img [src]="imageUrl"  style="width:250px;height:200px">
      <input type="file" (change)="fileChangeEvent($event)" placeholder="Upload a file..." multiple/>


   <button type="submit" >Submit</button>
 </form>

service ts.

 postFile(formData) {
  let headers = new Headers(); // Create headers

    return this.http.post(this.domain + '/postFile', formData)
    .map(res => res.json())
  }
  • Very obg, it worked by putting in fileChangeEvent function( ).

  • The page was updating when changing the input file?

  • No, only when sending the file.

  • It’s because I don’t understand. The function fileChangeEvent( ) triggers the sending of the image? I wanted to understand to formulate a response.

  • No, the person responsible for sending the image is this.filesToUpload in which it is called within Onsubmit(), but for some reason it updates the page.

1 answer

0


Place return false; at the end of the function where the sending of the files is done that will undo the refresh of the page. Ex.:

funcao{
   // códigos aqui
   return false;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.