简体   繁体   English

使用angular 4上传文件

[英]File upload using angular 4

I am trying to upload a file using angular 4, however it doesn't seem to work despite following keenly on tuitorial. 我正在尝试使用angular 4上传文件,但是尽管热衷于教程,但它似乎无法正常工作。 Can someone help to spot what I might be doing wrong and I will really appreciate. 有人可以帮我发现我可能做错了什么吗,我将非常感谢。 Below is my code: 下面是我的代码:

 import { Component, OnInit } from '@angular/core'; import { ConnectionManagerComponent } from 'src/app/connection-manager/connection-manager.component'; import { ViewChild } from '@angular/core'; import { FormGroup } from '@angular/forms'; import { FormBuilder } from '@angular/forms'; import { Router } from '@angular/router'; import { Validators } from '@angular/forms'; @Component({ selector: 'app-new-contact-list.component', templateUrl: './new-contact-list.component.html', styleUrls: ['./new-contact-list.component.css'] }) export class NewContactListComponent implements OnInit { @ViewChild(ConnectionManagerComponent) connectionManager:ConnectionManagerComponent; form:FormGroup; selectedFile: File; onFileChanged(event) { this.selectedFile = event.target.files[0] } constructor(private fb: FormBuilder,public router:Router) { this.form = this.fb.group({ name: ['', Validators.required], fileName: ['', Validators.required], }); } ngOnInit() { } addContactList() { const val = this.form.value; let contactListName = val.name; const fd = new FormData(); fd.append("name" ,contactListName); fd.append('file', this.selectedFile,this.selectedFile.name); console.log(fd); this.connectionManager.post('/contactGroups', res => { console.log(res); this.router.navigateByUrl('/newContactList'); },fd); } } 
  <div class="input-group"> <input style="display: none" id="fileName" formControlName="fileName" type="file" (change)="onFileChanged($event)" #fileInput> <button (click)="fileInput.click()">Select File</button> </div> 

Only file selection is happening there. 仅文件选择在那里发生。 The execution stops at onFileChanged() function. 执行在onFileChanged()函数处停止。 Try the snippet below for the onFileChanged() function. 尝试下面的onFileChanged()函数片段。 If it doesn't work. 如果不起作用。 Please mention the reference. 请提及参考。

onFileChanged(event) {
this.selectedFile = event.target.files[0];
addContactList();
}

File Process Upload In angular: 文件处理上传角度:

app.component.html app.component.html

<input #fileUpload type="file" id="fileUpload" style="" (change)="detectFiles($event)" (click)="fileUpload.value = null">

app.component.ts app.component.ts

import { Component } from '@angular/core';
import { HttpEvent, HttpEventType } from '@angular/common/http';
import { FileUploadService } from './fileUpload.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  constructor(private fileUploadService: FileUploadService) {

  }
  detectFiles(event) {
    if (event.target.files.length == 0) {
      console.log("No file selected!");
      return
    }
    let file: File = event.target.files[0];
    console.log("FILE DATA:",file);

    let uploadPath = "/home/upload/";

  this.fileUploadService.uploadFile(uploadPath, file).subscribe((event: HttpEvent<any>) => {
      switch (event.type) {
        case HttpEventType.Response:
          console.log(event.body);
      }
    });

  }
}

app.module.ts app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';

import { HttpClientModule } from '@angular/common/http';
import { FileUploadService } from './fileUpload.service';

@NgModule({
  imports:      [ BrowserModule, FormsModule, HttpClientModule],
  declarations: [ AppComponent, HelloComponent ],
  bootstrap:    [ AppComponent ],
  providers: [ FileUploadService ]
})
export class AppModule { }

fileUpload.service.ts fileUpload.service.ts

import { Inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams, HttpHeaders, HttpRequest } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Injectable()
export class FileUploadService {
  constructor(private http: HttpClient) {

  }

  uploadFile(uploadPath, fileToUpload: File) {
    const _formData = new FormData();
    _formData.append('file', fileToUpload, fileToUpload.name);
    _formData.append('uploadPath', uploadPath);

    const url = `api/v1/uploadFile`;

    const request = new HttpRequest('POST', url, _formData, {reportProgress: true });
    return this.http.request(request);
  }

}

Refer: https://stackblitz.com/edit/angular-rmpdhr?file=src%2Fapp%2FfileUpload.service.ts 请参阅: https : //stackblitz.com/edit/angular-rmpdhr?file=src%2Fapp%2FfileUpload.service.ts

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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