我知道这是一个非常普遍的问题,但我在Angular 2中上传文件失败了。 我试过了

1) http://valor-software.com/ng2-file-upload/

2) http://ng2-uploader.com/home

...但失败了。有人在Angular中上传过文件吗?你用了什么方法?怎么做呢?如果提供了任何示例代码或演示链接,将非常感谢。


当前回答

Angular 2对上传文件提供了很好的支持。不需要第三方库。

<input type="file" (change)="fileChange($event)" placeholder="Upload file" accept=".pdf,.doc,.docx">
fileChange(event) {
    let fileList: FileList = event.target.files;
    if(fileList.length > 0) {
        let file: File = fileList[0];
        let formData:FormData = new FormData();
        formData.append('uploadFile', file, file.name);
        let headers = new Headers();
        /** In Angular 5, including the header Content-Type can invalidate your request */
        headers.append('Content-Type', 'multipart/form-data');
        headers.append('Accept', 'application/json');
        let options = new RequestOptions({ headers: headers });
        this.http.post(`${this.apiEndPoint}`, formData, options)
            .map(res => res.json())
            .catch(error => Observable.throw(error))
            .subscribe(
                data => console.log('success'),
                error => console.log(error)
            )
    }
}

使用@angular/core": "~2.0.0"和@angular/http: "~2.0.0"

其他回答

我已经成功地使用了下面的工具。我和primeNg没有利害关系,只是传递我的建议。

http://www.primefaces.org/primeng/#/fileupload

我已经上传文件使用引用。以这种方式上传文件不需要包。

//要写入.ts文件的代码

@ViewChild("fileInput") fileInput;

addFile(): void {
let fi = this.fileInput.nativeElement;
if (fi.files && fi.files[0]) {
  let fileToUpload = fi.files[0];
    this.admin.addQuestionApi(fileToUpload)
      .subscribe(
        success => {
          this.loading = false;
          this.flashMessagesService.show('Uploaded successfully', {
            classes: ['alert', 'alert-success'],
            timeout: 1000,
          });
        },
        error => {
          this.loading = false;
          if(error.statusCode==401) this.router.navigate(['']);
          else
            this.flashMessagesService.show(error.message, {
              classes: ['alert', 'alert-danger'],
              timeout: 1000,
            });
        });
  }

}

//服务中要编写的代码。ts文件

addQuestionApi(fileToUpload: any){
var headers = this.getHeadersForMultipart();
let input = new FormData();
input.append("file", fileToUpload);

return this.http.post(this.baseUrl+'addQuestions', input, {headers:headers})
      .map(response => response.json())
      .catch(this.errorHandler);

}

//用HTML编写的代码

<input type="file" #fileInput>

今天我在我的angular 6应用中集成了ng2文件上传包,它非常简单,请找到下面的高级代码。

导入ng2-file-upload模块

app.module.ts

    import { FileUploadModule } from 'ng2-file-upload';

    ------
    ------
    imports:      [ FileUploadModule ],
    ------
    ------

组件的文件导入FileUploader

app.component.ts

    import { FileUploader, FileLikeObject } from 'ng2-file-upload';
    ------
    ------
    const URL = 'http://localhost:3000/fileupload/';
    ------
    ------

     public uploader: FileUploader = new FileUploader({
        url: URL,
        disableMultipart : false,
        autoUpload: true,
        method: 'post',
        itemAlias: 'attachment'

        });

      public onFileSelected(event: EventEmitter<File[]>) {
        const file: File = event[0];
        console.log(file);

      }
    ------
    ------

组件HTML添加文件标签

app.component.html

 <input type="file" #fileInput ng2FileSelect [uploader]="uploader" (onFileSelected)="onFileSelected($event)" />

Working Online stackblitz链接:https://ng2-file-upload-example.stackblitz.io

Stackblitz代码示例:https://stackblitz.com/edit/ng2-file-upload-example

官方文档链接https://valor-software.com/ng2-file-upload/

由于代码示例有点过时,我想我应该分享一个更近期的方法,使用Angular 4.3和新的HttpClient API @angular/common/http

export class FileUpload {

@ViewChild('selectedFile') selectedFileEl;

uploadFile() {
let params = new HttpParams();

let formData = new FormData();
formData.append('upload', this.selectedFileEl.nativeElement.files[0])

const options = {
    headers: new HttpHeaders().set('Authorization', this.loopBackAuth.accessTokenId),
    params: params,
    reportProgress: true,
    withCredentials: true,
}

this.http.post('http://localhost:3000/api/FileUploads/fileupload', formData, options)
.subscribe(
    data => {
        console.log("Subscribe data", data);
    },
    (err: HttpErrorResponse) => {
        console.log(err.message, JSON.parse(err.error).error.message);
    }
)
.add(() => this.uploadBtn.nativeElement.disabled = false);//teardown
}

尽量不要设置options参数

这个http post(美元(this。apiEndPoint), formData)

并且确保你没有在你的Http工厂中设置globalHeaders。