text 将文件从Angular发送到.net核心api控制器

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了text 将文件从Angular发送到.net核心api控制器相关的知识,希望对你有一定的参考价值。

Html:

<img id="r_image" class="cms-editable-element" [src]="promo?.r_image?promo?.r_image:'/Images/DickerData_Logo_BlackRed.png'"
            width="200" alt="" style="vertical-align: middle;"/>

<div id="cmsEditImageArea" style="display: none">
  <input class="file-upload" type='file' (change)="onSelectFile($event)">
  <div id="cmsSaveButton" class="cms-control-button">
    <a (click)="savePromoImage()">Save</a>
  </div>
  <div id="cmsCancelButton" class="cms-control-button">
    <a (click)="cancelSavePromoContent()">Cancel</a>
  </div>
</div>

Component:

formData = new FormData();
file: any;

onSelectFile(event): void {
  this.file = event.target.files[0];
}

savePromoImage(): void {

  this.formData.append(this.file.name, this.file);

  this.catalogueService.savePromoImage(this.editImagePromoModel.section_id, this.editImageType, this.formData)
    .subscribe((res: NewsletterSectionResponseModel) => {

    },
      (error: any) => {
        console.info(error);
      });
}

service:

savePromoImage(sectionId: string, type: string, image: any): Observable<NewsletterSectionResponseModel> {
  return this.http.post(this.base_url + "/savepromoimage?sectionId=" + sectionId + "&type=" + type, image)
    .pipe(catchError(this.handleError));
}

**Use post to transfer file to controller**

Api Controller:

#region SavePromoImage
[HttpPost("savepromoimage"), DisableRequestSizeLimit]
[NoCache]
[ProducesResponseType(typeof(NewsletterSectionResponseModel), 200)]
[ProducesResponseType(typeof(ApiResponse), 400)]
public IActionResult SavePromoImage(string sectionId, string type)
{
  //type ===> property name (model)
    try
    {
        var httpRequest = HttpContext.Request;
        if (httpRequest.Form.Files.Count > 0)
        {
            var uploadFile = httpRequest.Form.Files[0];  // get the uploaded file
            var postUrl = "http://webapi.dickerdata.com.au/api/newsletters/edit-newsletter-promo-image.json?lp-comp-code=" + Global.CompanyCode + "&section_id=" + sectionId;
            if (uploadFile != null && uploadFile.Length > 0)
            {
                Byte[] imageByte = new Byte[uploadFile.Length];
                using (var ms = new MemoryStream())
                {
                    uploadFile.CopyTo(ms);
                    imageByte = ms.ToArray();
                }
                string fileName = ContentDispositionHeaderValue.Parse(uploadFile.ContentDisposition).FileName.Trim('"');

                HttpClient httpClient = new HttpClient();
                MultipartFormDataContent form = new MultipartFormDataContent();
                form.Add(new ByteArrayContent(imageByte), type, fileName);

                var response = httpClient.PostAsync(postUrl, form).Result;

                httpClient.Dispose();

                return Ok(new NewsletterSectionResponseModel
                {
                    status = true,
                    content = "Promo Image uploaded."
                });
            }
        }

        return Ok(new NewsletterSectionResponseModel
        {
            status = false,
            content = "Upload file is empty"
        });
    }
    catch (Exception ex)
    {
        return BadRequest(new ApiResponse
        {
            Status = false,
            ResponseMessage = "Invalid file. <br /> Unable to upload promo image."
        });
    }
}
#endregion

以上是关于text 将文件从Angular发送到.net核心api控制器的主要内容,如果未能解决你的问题,请参考以下文章

如何配置 .net 核心以将身份验证 cookie 发送到不同的域

如何从.net核心应用程序向服务总线主题发送消息

未发送从 Angular 到 .Net 5 webapi 的发布参数

从 Angular 发布到 .net WebAPI

Angular + core 如何将文件数组从 Angular 上传到 Dot Net Core

text 使用ASP.NET Core 2 Web API,Angular 5,.NET核心身份和Facebook登录进行JWT身份验证