【问题标题】:ASP .NET MVC Data type for image图像的 ASP .NET MVC 数据类型
【发布时间】:2022-01-05 17:03:40
【问题描述】:

我想上传一张图片,然后将其转换为base64。

我应该选择什么数据类型?我尝试了字符串,但它只给了我文件名而不是它的路径。

public class TestModel
{
    public string Image { get; set; }
}

查看:

@model Test.Models.TestModel

<form asp-action="Test" method="post">

        <div class="form-group">
            <input asp-for="Image" class="form-control" type="file" />
        </div>

        <div class="form-group">
            <input type="submit" value="Create" class="btn btn-primary" />
        </div>
    </form>

【问题讨论】:

  • 你应该使用 byte[]
  • @daremachine 如果我把它改成 public byte[] Image { get;放;我得到一个“值'test.png'对图像无效。”表单页面上的消息。
  • 阅读教程并了解有关 asp 核心文件上传的更多信息。互联网上有很多教程,包括微软页面。
  • 你只得到文件名,因为你的表单没有enctype="multipart/form-data"developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/…

标签: c# asp.net-core asp.net-core-mvc


【解决方案1】:

您可以使用IFormFile 类型上传图片,然后在控制器中将其转换为base64。这是我的代码:

控制器

  public IActionResult FileUpLoad(Models.TestModel model)
        {
            //convert it to base64
            var ms = new MemoryStream();
            model.Image.CopyTo(ms);
            var fileBytes = ms.ToArray();
            string result = Convert.ToBase64String(fileBytes);

            //......
            
            return RedirectToAction("Index");
        }

型号

public class TestModel

    {
       
        public IFormFile Image { get; set; }
    }

查看

<div>
    
    <form asp-controller="Home" asp-action="FileUpLoad" enctype="multipart/form-data" method="post">
       
        <input type="file" asp-for="Image" />
        <button type="submit">Submit</button>
    </form>
</div>

上传图片,然后可以将其转换为base64。

【讨论】:

    猜你喜欢
    • 2016-08-04
    • 2019-10-22
    • 1970-01-01
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多