【问题标题】:400 Bad Request Error When trying to Pass object with image to Server尝试将带有图像的对象传递给服务器时出现 400 错误请求错误
【发布时间】:2023-03-28 22:31:02
【问题描述】:

在我的应用程序中,我试图将一个包含图像的对象传递给 Web api,但它会引发 400 bad request 错误并挑出scanImage 属性作为罪魁祸首。我已经尝试了很多解决方法并在 Google 上搜索了很多,但还没有找到任何帮助。

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; }
    }

应用服务

        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。请帮我。这几天我一直在做这个。

【问题讨论】:

  • 好的,由于您使用的是JSON.stringify 而不是multipart 形式,它不会绑定到IFormFile。您应该将其转换为 base64 字符串并将其发送。
  • @aaron 好的,在您回复之前,我想尝试在打字稿中转换为字节或 uint8Array。你怎么看?
  • 你可能还需要一个 base64 字符串来表示JSON.stringify
  • 好的。让我试试看。如果我还需要帮助,我会提醒你。

标签: angular rest typescript aspnetboilerplate


【解决方案1】:

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

参考 => Uploading Image in Aspnet boilerplate

【讨论】:

  • 感谢您的回复。我尝试了亚伦的建议,它对我有用。我所做的是在客户端将文件转换为base64string,将其传递给web api并将字符串转换为字节并保存。
  • 是的,这是另一种解决方案;)
猜你喜欢
  • 2012-12-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-13
  • 1970-01-01
  • 2016-06-14
  • 1970-01-01
  • 2021-02-11
  • 2021-03-23
相关资源
最近更新 更多