以angular5上传图片

时间:2018-01-30 20:43:25

标签: file-upload angular5

我有这段代码在angular4

中运行良好
 public SetHeaders(page?: number, itemsPerPage?: number, image?: boolean) {

    let tokenValue = "Bearer " + this._OidcSecurityService.getToken();
    if (!image) {
        this.headers = new HttpHeaders({
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'Authorization': tokenValue,
            'Pagination': page + "," + itemsPerPage
        });
    } else if (image) {
        //this.headers.delete('Content-Type');
        //this.headers.delete('Accept');
        this.headers = new HttpHeaders({
           'Authorization': tokenValue
        });
    }

}

我向上移动到角度5,现在​​以下部分不再起作用了

else if (image) {
        //this.headers.delete('Content-Type');
        //this.headers.delete('Accept');
        this.headers = new HttpHeaders({
           'Authorization': tokenValue
        });
    }

以下方法检索用户输入并创建在dataservice上传递的formdata对象

AdmitStudent() {
    this.GetStudentPicture();
    this.url = this.admissionResourceApiUrl + "AdmitStudent";
    this._dataService.SetHeaders(0, 0, true);

    let input = new FormData();
    input.append("stdpic", this.admissionModel.Picture);
    this._dataService.AddRecord(this.url, this.admissionModel)
        .subscribe((resp => {
            this.response = resp.result;
            if (this.response == "OK") {
                this.admissionModel = new StudentViewModel();
                this.GetAdmissions(this.clsGrp.ProgrammeID, this.vacancyInfo.Term.TermID, this.clsGrp.StageID);
            }
        }))
}

这是我从用户那里检索图片的地方

private GetStudentPicture() {
    let stdpicElement = this.stdpic.nativeElement;
    if (stdpicElement.files && stdpicElement.files[0]) {
        this.admissionModel.Picture = stdpicElement.files[0];
    }
}

以下是dataservice中发送帖子请求的方法

public AddRecord<T>(url: string, model: Object) {
    return this._http.post<T>(url, model, { headers: this.headers, observe: 'response' })
        .map(res => {
            this.dataModel.result = res.statusText;
            return this.dataModel;
        },this.handleError);
}

0 个答案:

没有答案