【问题标题】:Image transfer between Angular and Web API CoreAngular 和 Web API Core 之间的图像传输
【发布时间】:2018-07-15 02:05:09
【问题描述】:

从 3 天开始,我一直在尝试在 Angular 和 Web api 核心之间进行图像传输,反之亦然,但我无法这样做。我已经在互联网上搜索了很多,但我没有找到任何 web api core 的示例。

如果有人能给我提供文档/示例或一些教程的链接,我将不胜感激。

现在我正在通过 Json 对象在 Angular 和 API 之间进行数据传输。如何将图像转换为 json 进行传输?

很抱歉,这是一个基本问题,因为我是新手。

【问题讨论】:

  • 你现在遇到了什么错误?

标签: angular image asp.net-core-webapi transfer


【解决方案1】:

为什么要将图像转换为 JSON?

您将文件直接传输到服务。这就是想法。控制器接收提交的文件POST

后台

    using System.Net.Http.Headers;

                [HttpPost]
            public ActionResult UploadFile()
            {
                try
                {
                    var file = Request.Form.Files[0];

                    if (file.Length > 0)
                    {
                        string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName;
                        string fullPath = Path.Combine(@"C:\wwwroot\upload", fileName);
                        using (var stream = new FileStream(fullPath, FileMode.Create))
                        {
                            file.CopyTo(stream);
                        }
                    }
                    return Json("OK");
                }
                catch (System.Exception ex)
                {
                    return Json("Failed");
                }
            }

前端

export class UploadComponent {
  constructor(private http: HttpClient) { }

  upload(files) {
    if (files.length === 0)
      return;

    const formData = new FormData();

    for (let file of files)
      formData.append(file.name, file);

    const uploadReq = new HttpRequest('POST', `api/uploadFile`, formData);

    this.http.request(uploadReq).subscribe(event => {
      if (event.type === HttpEventType.Response)
        //DONE
    });
  }
}

HTML

<input #file type="file" (change)="upload(file.files)" />

【讨论】:

  • @NoumanArshad 最后,你解决了你的问题吗?如果我的回答解决了你的问题,别忘了标记答案。
  • 抱歉,我出站了。在您的示例中,我们正在将图像上传到 API ..如何从 api 获取图像到前端?
猜你喜欢
  • 1970-01-01
  • 2023-03-20
  • 2020-01-14
  • 1970-01-01
  • 2017-11-01
  • 2017-09-07
  • 1970-01-01
  • 2020-03-15
  • 2021-12-25
相关资源
最近更新 更多