file upload在Angular 2中?

我知道这是一个普遍的问题,但我没有上传Angular 2中的文件。我试过了

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

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

…但失败了 有没有人上传Angular 2的文件? 你用什么方法? 怎么做? 如果提供任何示例代码或演示链接,将非常感激。 谢谢。

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(); /** No need to include Content-Type in Angular 4 */ 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“

感谢@Eswar。 这段代码完全适合我。 我想添加一些东西到解决scheme:

我得到错误: java.io.IOException: RESTEASY007550: Unable to get boundary for multipart

为了解决这个错误,你应该删除“Content-Type”“multipart / form-data”。 它解决了我的问题。

我已经使用了以下工具从成功启动。 primeNg游戏中没有皮肤,只是传递我的build议。

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

由于代码示例有点过时,我想我会分享一个更新的方法,使用Angular 4.3和新的(er)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 } 

在Angular 2+中,将Content-Type留空是非常重要的 。 如果将“Content-Type”设置为“multipart / form-data”,则上传不起作用!

upload.component.html

 <input type="file" (change)="fileChange($event)" name="file" /> 

upload.component.ts

 export class UploadComponent implements OnInit { constructor(public http: Http) {} fileChange(event): void { const fileList: FileList = event.target.files; if (fileList.length > 0) { const file = fileList[0]; const formData = new FormData(); formData.append('file', file, file.name); const headers = new Headers(); // It is very important to leave the Content-Type empty // do not use headers.append('Content-Type', 'multipart/form-data'); headers.append('Authorization', 'Bearer ' + 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9....'); const options = new RequestOptions({headers: headers}); this.http.post('https://api.mysite.com/uploadfile', formData, options) .map(res => res.json()) .catch(error => Observable.throw(error)) .subscribe( data => console.log('success'), error => console.log(error) ); } } } 

这个简单的解决scheme为我工作: file-upload.component.html

 <div> <input type="file" #fileInput placeholder="Upload file..." /> <button type="button" (click)="upload()">Upload</button> </div> 

然后用XMLHttpRequest直接在组件中上传。

 import { Component, OnInit, ViewChild } from '@angular/core'; @Component({ selector: 'app-file-upload', templateUrl: './file-upload.component.html', styleUrls: ['./file-upload.component.css'] }) export class FileUploadComponent implements OnInit { @ViewChild('fileInput') fileInput; constructor() { } ngOnInit() { } private upload() { const fileBrowser = this.fileInput.nativeElement; if (fileBrowser.files && fileBrowser.files[0]) { const formData = new FormData(); formData.append('files', fileBrowser.files[0]); const xhr = new XMLHttpRequest(); xhr.open('POST', '/api/Data/UploadFiles', true); xhr.onload = function () { if (this['status'] === 200) { const responseText = this['responseText']; const files = JSON.parse(responseText); //todo: emit event } else { //todo: error handling } }; xhr.send(formData); } } } 

如果您使用的是dotnet核心,则参数名称必须与字段名称匹配。 这种情况下的文件:

 [HttpPost("[action]")] public async Task<IList<FileDto>> UploadFiles(List<IFormFile> files) { return await _binaryService.UploadFilesAsync(files); } 

这个答案是http://blog.teamtreehouse.com/uploading-files-ajax的声明;

编辑 :上传后,你必须清除file upload,以便用户可以select一个新的文件。 而不是使用XMLHttpRequest,也许最好使用fetch:

 private addFileInput() { const fileInputParentNative = this.fileInputParent.nativeElement; const oldFileInput = fileInputParentNative.querySelector('input'); const newFileInput = document.createElement('input'); newFileInput.type = 'file'; newFileInput.multiple = true; newFileInput.name = 'fileInput'; const uploadfiles = this.uploadFiles.bind(this); newFileInput.onchange = uploadfiles; oldFileInput.parentNode.replaceChild(newFileInput, oldFileInput); } private uploadFiles() { this.onUploadStarted.emit(); const fileInputParentNative = this.fileInputParent.nativeElement; const fileInput = fileInputParentNative.querySelector('input'); if (fileInput.files && fileInput.files.length > 0) { const formData = new FormData(); for (let i = 0; i < fileInput.files.length; i++) { formData.append('files', fileInput.files[i]); } const onUploaded = this.onUploaded; const onError = this.onError; const addFileInput = this.addFileInput.bind(this); fetch('/api/Data/UploadFiles', { credentials: 'include', method: 'POST', body: formData, }).then((response: any) => { if (response.status !== 200) { const error = `An error occured. Status: ${response.status}`; throw new Error(error); } return response.json(); }).then(files => { onUploaded.emit(files); addFileInput(); }).catch((error) => { onError.emit(error); }); } 

https://github.com/yonexbat/cran/blob/master/cranangularclient/src/app/file-upload/file-upload.component.ts

这是有用的教程 ,如何使用ng2-file-upload和WITHOUT ng2-file-upload来上传文件。

对我来说,它有很大的帮助。

目前,教程包含一些错误:

1-客户端应该有一个相同的上传url作为服务器,所以在app.component.ts更改行

const URL = 'http://localhost:8000/api/upload';

const URL = 'http://localhost:3000';

2-服务器发送响应为“文本/ HTML”,所以在app.component.ts更改

 .post(URL, formData).map((res:Response) => res.json()).subscribe( //map the success function and alert the response (success) => { alert(success._body); }, (error) => alert(error)) 

 .post(URL, formData) .subscribe((success) => alert('success'), (error) => alert(error));