400错误尝试将带有图像的对象传递给服务器时出错

时间:2017-11-09 09:58:17

标签: angular rest typescript aspnetboilerplate

在我的应用程序中,我试图将包含图像的对象传递给web api,但它会抛出400错误的请求错误并选择scanImage属性作为罪魁祸首。我已经尝试了很多变通办法并搜索了很多内容,但还没有找到任何帮助。

DTO

    public class CreateTaxMapDto
    {
        [Required(ErrorMessage = "Tax Type is required")]
        public int TaxTypeId { get; set; }

        public int? BranchId { get; set; }

        [Required(ErrorMessage = "Date of receipt is required")]
        public DateTime DateOfReceipt { get; set; }

        public decimal Amount { get; set; }

        public IFormFile ScanImage { get; set; }

        [StringLength(150)]
        public string Remark { get; set; }
    }

ApplicationService

        public async Task SaveTax(CreateTaxMapDto input)
        {
            // Code to save the input to the database
        }

CreateTaxMap.ts

export class CreateTaxMapDto {
    taxTypeId: number;
    branchId: number;
    dateOfReceipt: Date;
    amount: number;
    scanImage: any;
    constructor(data?: any) {
        if (data !== undefined) {
            this.taxTypeId = data['taxTypeId'] !== undefined ? data['taxTypeId'] : null;
            this.branchId = data['branchId'] !== undefined ? data['branchId'] : null;
            this.dateOfReceipt = data['dateOfReceipt'] !== undefined ? data['dateOfReceipt'] : null;
            this.amount = data['amount'] !== undefined ? data['amount'] : null;
            this.scanImage = data['scanImage'] !== undefined ? data['scanImage'] : null;
        }
    }

    static fromJS(data: any): CreateTaxMapDto {
        return new CreateTaxMapDto(data);
    }

    toJS(data?: any) {
        data = data === undefined ? {} : data;
        data['taxTypeId'] = this.taxTypeId !== undefined ? this.taxTypeId : null;
        data['branchId'] = this.branchId !== undefined ? this.branchId : null;
        data['dateOfReceipt'] = this.dateOfReceipt !== undefined ? this.dateOfReceipt : null;
        data['amount'] = this.amount !== undefined ? this.amount : null;
        data['scanImage'] = this.scanImage !== undefined ? this.scanImage : null;

        return data;
    }

    toJSON() {
        return JSON.stringify(this.toJS());
    }

clone() {
    const json = this.toJSON();
    return new CreateTaxMapDto(JSON.parse(json));
}

}

创建-Tax.Component.Html

<input #imageInput type="file" class="form-control" (change)="onImageChange()" />

Component.ts

  onImageChange() {
    let imgInput = this.imageInput.nativeElement;
    if (imgInput.files && imgInput.files[0]) {
      this.file = imgInput.files[0];
    }
  }

save(): void {
    this.saving = true;
    this.tax.branchId = this.appSession.user.branchId;
    const custFile = <MyFile>(this.file); // MyFile is an interface that extends File
    let originalFile = {
      'lastModified': custFile.lastModified,
      'lastModifiedDate': custFile.lastModifiedDate,
      'name': custFile.name,
      'size': custFile.size,
      'type': custFile.type,
      'webkitRelativePath': custFile.webkitRelativePath
    };
    this.tax.scanImage = originalFile;
    console.log(this.tax.scanImage);
    this._taxService.create(this.tax)
        .finally(() => { this.saving = false; })
        .subscribe(() => {
            this.notify.success(this.l('SavedSuccessfully'), 'Tax Saved');
            this.close();
            this.modalSave.emit(null);
        });
  }

Service.ts

create(input: CreateTaxMapDto): Observable<TaxDto> {
        let url_ = this.baseUrl + '/api/services/app/Tax/SaveTax';

        const content_ = JSON.stringify(input ? input.toJS() : null);
        console.log('Inputt: ' + content_);

        return this.http.request(url_, {
            body: content_,
            method: 'post',
            headers: new Headers({
                'Content-Type': 'application/json; charset=UTF-8',
                'Accept': 'application/json; charset=UTF-8'
            })
        }).map((response) => {
            return this.processCreate(response);
        }).catch((response: any, caught: any) => {
            if (response instanceof Response) {
                try {
                    return Observable.of(this.processCreate(response));
                } catch (e) {
                    return <Observable<TaxDto>><any>Observable.throw(e);
                }
            } else
                return <Observable<TaxDto>><any>Observable.throw(response);
        });
    }

控制台上的错误如下

> {code: 0, message: "Your request is not valid!", details: "The
> following errors were detected during validation. ↵ -  ↵",
> validationErrors: Array(1)} code : 0 details : "The following errors
> were detected during validation. ↵ -  ↵" message : "Your request is
> not valid!" validationErrors : Array(1) 0 : members : ["scanImage"]
> message : ""
> __proto__ : Object length : 1
> __proto__ : Array(0)
> __proto__ : Object

我使用aspnetboilerplate v3.0.0 .NET Core + Angular4。请帮我。我已经在这几天了。

1 个答案:

答案 0 :(得分:0)

我建议你创建一个基于AbpController的控制器。 然后通过此控制器上传图像并返回图像唯一文件名。然后在CreateTaxMapDto中使用该唯一文件名。

参考=&gt; Uploading Image in Aspnet boilerplate