栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用Angular2将文件上传到REST API

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Angular2将文件上传到REST API

在最终版本中,这实际上很容易做到。花了我一些时间来解决这个问题,因为我遇到的有关它的大多数信息都已过时。如果其他人为此感到困扰,请在此处发布我的解决方案。

import { Component, ElementRef, Input, ViewChild } from '@angular/core';import { Http } from '@angular/http';@Component({    selector: 'file-upload',    template: '<input type="file" [multiple]="multiple" #fileInput>'})export class FileUploadComponent {    @Input() multiple: boolean = false;    @ViewChild('fileInput') inputEl: ElementRef;    constructor(private http: Http) {}    upload() {        let inputEl: HTMLInputElement = this.inputEl.nativeElement;        let fileCount: number = inputEl.files.length;        let formData = new FormData();        if (fileCount > 0) { // a file was selected for (let i = 0; i < fileCount; i++) {     formData.append('file[]', inputEl.files.item(i)); } this.http     .post('http://your.upload.url', formData)     // do whatever you do...     // subscribe to observable to listen for response        }    }}

然后像这样使用它:

<file-upload #fu (change)="fu.upload()" [multiple]="true"></file-upload>

这就是全部。

或者,捕获事件对象并从srcElement获取文件。老实说,不确定是否有任何方法比其他方法更好!

请记住,FormData是IE10 +,因此,如果必须支持IE9,则需要使用polyfill。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/420464.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号