user8885733
user8885733

Reputation: 147

Uploading a file using angular 4

I am trying to upload a excel file using angular 4 and add the data of the file in my database through node. I have written the angular code but nothing happens when I click on my upload button. neither the route is called nor there is any error. Please could you look into my code and tell me where I am going wrong

My Upload Service:

constructor(public http: Http) {}

 uploadFile(formData) {
   const url  = 'http://localhost:3000/upload';
   console.log('here');
    return this.http.post(url, formData);
  }

My typescript file :

import {Component, ElementRef, OnInit} from '@angular/core';
import {FileUploadService} from './file.upload.service';



@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  private elemRef: ElementRef;

  constructor(public fileUploadService: FileUploadService) {
   }

  ngOnInit() {
  }

  uploadFile() {
    const files = this.elemRef.nativeElement.querySelector('#file').files;
    const formData = new FormData();
    const file = files[0];
    formData.append('file', file);
    this.fileUploadService.uploadFile(formData).subscribe(
       (response) => {
       console.log(response.json());
       }
    );

  }
}

My html code:

<form>
  <div class="form-group">
    <label for="file">single</label>
    <input id= "file"
       type="file"
       class="form-control"
       name="single"
        />
    <button (click)="uploadFile()">Upload</button>
  </div>
 </form>

I have included the service in my app.module providers and everything

Upvotes: 1

Views: 779

Answers (1)

user4676340
user4676340

Reputation:

You're using Angular, why don't you take advantage of it ?

Using this

this.elemRef.nativeElement.querySelector('#file').files;

Is counter-productive. Instead, use this

<!-- HTML -->
<input id= "file"
   type="file"
   class="form-control"
   name="single"
   #uploadInput
/>

// TypeScript
@ViewChild() uploadInput: ElementRef;
const files = (this.uploadInput.nativeElement as HTMLInputElement).files; // remove the 'as' clause if you want

Now, about your issue : Could you try deleting your form tag ? I guess that the button is validating your form, but really, that's throwing a stone in the lake here. Could you post the whole code of your HTML and CSS ? Maybe you forgot something elsewhere, because otherwise, I don't see any issue (provided that you actually select a file and not cancel, because you have no condition in your code to prevent a cancel)

Upvotes: 1

Related Questions