如何将数据和图像都传递到"ASP.NET Core"?使用Angular 2(打字稿)的Web API? [英] How to pass data and image both to "ASP.NET Core" Web API using Angular 2(typescript)?

查看:112
本文介绍了如何将数据和图像都传递到"ASP.NET Core"?使用Angular 2(打字稿)的Web API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有只可以将数据传递给Web API的代码,但是我想在相同请求中传递数据和图像,而不是在使用angular 2 +打字稿和ASP.Net Core Web API的不同请求中传递数据和图像

I have code that can pass data only to web API but i want to pass data and Image both in same request not in different request using angular 2 + typescript and in ASP.Net Core Web API.

我的代码,将数据传递给API:

My Code to pass data to API:

角度代码:

   create(user) {
    return this.authHttp.post(this._baseUrl + 'user/', JSON.stringify(userData)).map((res: Response) => {
        return res;
    }).catch(this.configService.handleError);
}

API代码:

    [HttpPost]
    public IActionResult Create([FromBody]UserModel user)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        //save user
        _userRepository.Add(user);
        _userRepository.Commit();

        return new OkObjectResult(user.UserId);
    }

推荐答案

解决方案1:

最简单的方法是将图像作为 base64字符串.

The simplest way is sending the image as a base64 string.

只需创建一个简单的JavaScript函数即可读取文件并将其转换为 onchange <input>上的事件将为您完成工作.

Just create a simple JavaScript function to read the file and convert it to base64 string. Do it before sending the file - probably onchange event on the <input> will do the job for you.

然后,您可以将其直接存储在DB中(或根据需要另存为服务器上的文件).

Then you can store it directly in DB (or save as a file on the server if you need).

存储为base64字符串的图像可以通过浏览器直接发送回并显示,而无需其他操作,例如:

Image stored as base64 string can be send back and displaed directly by browser without additional actions, for example:

<img src="data:image/bmp;base64,[base64EncodedImageHere]" />


解决方案2:

前端:

如果您使用HTML5和文件上传控件,只需将表单编码设置为multipart/form-data:

If you are using HTML5 and a file upload control, just set form encoding as multipart/form-data:

<form method="post" enctype="multipart/form-data">

后端:

您模型中的属性应为IFormFile类型,然后您可以将文件保存在服务器上:

Your property in the model should have type IFormFile, then you can save the file on the server:

IFormFile file;

using (var fileStream = File.Create( [file path here] ))
{
    await file.CopyToAsync(fileStream);
    await fileStream.FlushAsync();
}

这篇关于如何将数据和图像都传递到"ASP.NET Core"?使用Angular 2(打字稿)的Web API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆