文件上传在Angular 2中? [英] File Upload In 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 =上传文件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();
/ **不需要在Angular 4中包含Content-Type * /
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 => ;
.subscribe(
data => console.log('success'),
error => console.log(error)
)
$ / code>
使用@ angular / core:〜2.0 .0和@ angular / http:〜2.0.0
I know this is very a general question but I am failing to upload a file in Angular 2. I have tried
1) http://valor-software.com/ng2-file-upload/ and
2) http://ng2-uploader.com/home
...but failed. Has anyone uploaded a file in Angular 2 ? What method did you use ? How to do so ? If any sample code or demo link is provided it will be really appreciated. Thank you.
Angular 2 provides good support for uploading file. Any third party library is not required.
<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)
)
}
}
using @angular/core": "~2.0.0" and @angular/http: "~2.0.0"
这篇关于文件上传在Angular 2中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!