如何为图像制作 POST 方法?

How to make a POST method for an image?

所以我一直在研究这个 API,直到现在我尝试弄清楚如何制作一个将图像作为参数的 POST 方法时才遇到问题。从理论上讲,它应该是这样工作的:

从网页上传图像,然后使用到 API 的路由,图像信息将像这样发送到数据库:

现在,我一直在不同的几个页面上寻找这个问题的答案,但 none 确实有帮助。事实上,我找到的唯一指南是关于将该方法集成到 Web Api(参见 https://www.c-sharpcorner.com/article/uploading-image-to-server-using-web-api-2-0/),但这对我来说并不适用,因为我无法继承一些我的解决方案中的方法。例如,使用上面的 link,我遇到了 HttpContext.Current 的问题,我猜这是因为我当前使用的解决方案。但是,这是另一个要问的问题。

所以我的方法看起来很像这样:

public class RecipeController : Controller
{
    private readonly Func<SqlConnection> _connFactory;
    public RecipeController(Func<SqlConnection> connFactory)
    {
        _connFactory = connFactory;
    }

    [Route("v1/recipe/{recipeBy}")]
    [HttpGet()]
    public List<Recipe> GetRecipes(string recipeBy)
    {
        using (var con = _connFactory())
        {
            con.Open();
            return con.Query<Recipe>("SELECT * FROM dbo.Recipe WHERE RecipeBy = @recipeBy", new { recipeBy }).ToList();
        }
    }
    ....

我正在使用 Dapper 将值传递到数据库。

因此,我的问题是:如何编写一个POST方法,将上传的图片作为参数,然后将其传递给数据库?我确实意识到这个问题很模糊,因为我什至没有提供可重现的代码。问题是,直到现在我什至都没有找到开始工作的正确方法,所以我无法真正提供任何有用的代码来帮助我。任何提示、提示、建议、教程...欢迎任何内容!

您可以通过使用 Html5 FileReader class 在客户端将图像读取为字符串然后 post 将其读取到 api 来完成此操作终点:

function UploadImage()
{
    var file = input[0].files[0];

    var reader = new FileReader();

    reader.onloadend = function () {
        var imageDataString = reader.result;
        // post the fileString value to your api here
    }

    if (file) {
        reader.readAsDataURL(file);
    }
}

然后在您的控制器上将 Base64String 转换为 byte[] 并将其存储在您的数据库中:

if (imageDataString != null && imageDataString != String.Empty)
{
    string imageDataParsed = imageDataString.Substring(imageDataString.IndexOf(',') + 1);
    byte[] imageBytes = Convert.FromBase64String(imageDataParsed);
}