简体   繁体   English

将文件从 Angular 上传到 .Net

[英]Upload File from Angular to .Net

I am trying make a post with my form along with a file.我正在尝试使用我的表单和文件发布帖子。 I tried see others posts but without result.我尝试查看其他帖子但没有结果。 If I make the post without the file, works just fine.如果我在没有文件的情况下发布帖子,就可以了。 English is not my native language, sorry for any mistakes.英语不是我的母语,如有错误请见谅。

This is the error:这是错误:

在此处输入图像描述

This is my data:这是我的数据:

在此处输入图像描述

My code -> .Net我的代码-> .Net

Model:模型:

public class EmailDto
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Subject { get; set; }
        public int? RecurrentDay { get; set; }
        public DateTime? SendDate { get; set; }
        public short SendHour { get; set; }
        public int? GroupId { get; set; }
        public int? RecipientTypeId { get; set; }
        public int? ListTypeId { get; set; }
        public bool SendForce { get; set; }
        public string? Recipients { get; set; }
        public bool Archived { get; set; }
        public bool Active { get; set; }
        public int IdTemplate { get; set; }
        public TemplateDto Template { get; set; }
        public int? IdRecurrence { get; set; }
        public IFormFile? File { get; set; }
    }

Controller:控制器:

[HttpPost("create")]
        public async Task<ActionResult> CreateEmail([FromBody] EmailDto email)

Angular ->角->

Model:模型:

export class EmailModel {
    id!: number
    idTemplate!: number
    idRecurrence!: number
    name!: string   
    subject!: string
    active!: boolean
    groupId!: number
    recipientTypeId!: number
    listTypeId! : number
    recipients!: string
    sendHour!: number
    sendForce!: boolean
    template!: TemplateModel
    file!: File
}

email.component.ts:电子邮件.component.ts:

onFileSelected(event: any) {
    let fileList: FileList = event.target.files;
    if (fileList.length > 0) {
      this.file = fileList[0];
    }
  }

async onSubmit() {
    if (this.file != null) {
      this.email.file = this.file;
      let headers = new HttpHeaders();
      headers.append('Content-Type', 'multipart/form-data');
      headers.append('Accept', 'application/json');
      this.createEmail(this.email, headers);
    } else {
      this.createEmail(this.email);
    }
  }

createEmail(email: EmailModel, headers?: HttpHeaders) {
    if (headers != null) {
      this.EmailService.CreateEmail(email, headers).subscribe(() => {
        this.isCreated = true;
      }), (error: any) => {
        console.log(error);
      }
    } else {
      this.EmailService.CreateEmail(email).subscribe(() => {
        this.isCreated = true;
      }), (error: any) => {
        console.log(error);
      }
    }
  }

service:服务:

CreateEmail(data: EmailModel, headers?: HttpHeaders) {
        return this.http.post(`${this.emailApi}/create`, data, {headers: headers});
    }

The last print:最后打印:

在此处输入图像描述

If I understood your problem correctly, it would seem you are trying to send a JSON object body with a file and, on the .NET side, it can't deserialize it.如果我正确理解了您的问题,您似乎正在尝试发送带有文件的 JSON 对象主体,并且在 .NET 端,它无法反序列化它。

You could try to send the file as base64 instead of whatever you are attempting to send it as now:您可以尝试将文件作为 base64 发送,而不是像现在一样尝试发送:

async onSubmit() 
{
    if (this.file == null) 
    {
        this.createEmail(this.email);
        return;
    }
    
    // Create a file reader
    const fileReader = new FileReader();
    // Tell the file reader what to do once it loads
    fileReader.onload = (event) => 
    {
        // which is to give us the base64 representation of the file
        const base64File = event.target.result.toString();
        // and assign it to the dto
        this.email.file = base64File;
        // before sending the request.
        this.createEmail(this.email);
    }; 
    // Finally, read the file.
    fileReader.readAsBinaryString(this.file);
}

Of course, you need to change file to a string in your DTOs.当然,您需要将file更改为 DTO 中的字符串。 You can then parse the base64 back to binary and do whatever you want with it.然后,您可以将 base64 解析回二进制文件并使用它做任何您想做的事情。 If you need IFormFile, then:如果您需要 IFormFile,则:

[HttpPost("create")]
public async Task<ActionResult> CreateEmail([FromBody] EmailDto email)
{
    var byteArray = Convert.FromBase64String(email.File);
    IFormFile file;
    using(var memoryStream = new MemoryStream(byteArray))
    {
        file = new FormFile(memoryStream, 
                            0, 
                            byteArray.Length, 
                            "someName", 
                            "someFileName");
    }

    ...
    doWhatever
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM