简体   繁体   中英

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

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:

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.

You could try to send the file as base64 instead of whatever you are attempting to send it as now:

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. You can then parse the base64 back to binary and do whatever you want with it. If you need IFormFile, then:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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