繁体   English   中英

ASP.NET 核心如何上传图片到SQL服务器数据库?

[英]ASP.NET Core how to upload image to SQL Server database?

我正在尝试做一个简单的应用程序来将用户注册到具有姓名、个人资料照片等的数据库,然后编辑或删除它们。 我打算将图像上传为IFileForm ,然后将其转换为 SQL 服务器的varbinary 但是我在如何实现上传图片方面遇到了问题。 该代码适用于其他成员。 任何帮助,将不胜感激。

我的用户 model class 为 API

public partial class User
{
    public string UserId { get; set; };
    public string UserName { get; set; };
    public string UserSurname { get; set; };
    public string UserBirthdate { get; set; };
    public byte[] UserPicture { get; set; };
}

我的API的发帖方法

public async Task<ActionResult<User>> PostUser(User user)
{
    _context.UserTable1s.Add(user);

    try
    {
        await _context.SaveChangesAsync();
    }
    catch (DbUpdateException)
    {
        if (UserExists(user.UserId))
        {
             return Conflict();
        }
        else
        {
            throw;
        }
    } 

    return CreatedAtAction("GetUser", new { id = user.UserId }, user);
}

我的用户 model 为 Web App

public class User
{
    public string UserId { get; set; }
    public string UserName { get; set; }
    public string UserSurname { get; set; }
    public string UserBirthdate { get; set; }
    public IFormFile UserPicture { get; set; }
}

Web App消费API的post方法

public async Task<IActionResult> AddUser(User user)
{
    User receivedUser = new User();

    using (var httpClient = new HttpClient())
    {
        StringContent content = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json");

        using (var response = await httpClient.PostAsync("https://localhost:7252/api/Users", content))
        {
            string apiResponse = await response.Content.ReadAsStringAsync();
            receivedUser = JsonConvert.DeserializeObject<User>(apiResponse);
        }
    }

    return View(receivedUser);
}

最后是 AddUser 的视图。 删除了其他成员的代码,因为太长了。

 <div class="col-md-4">
        <form asp-action="AddUser" enctype="multipart/form-data">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            /*some more code here for other members*/
            <div class="form-group">
                <label asp-for="UserPicture" type="file"class="control-label">User Picture</label>
                <input asp-for="UserPicture" type="file" class="form-control" />
                <span asp-validation-for="UserPicture" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>

编辑:稍微编辑一下 vega_gf 的答案后,我设法让它工作。 我很确定这不是最佳方式,但现在可以使用。

我现在的 AddUser 方法:

public async Task<IActionResult> AddUser(User user, [FromForm]IFormFile imgfile)
{
    User receivedUser = new User();
    using (var httpClient = new HttpClient())
    {
            if (imgfile != null)
            {
                using var dataStream = new MemoryStream();
                await imgfile.CopyToAsync(dataStream);
                byte[] imageBytes = dataStream.ToArray();
                string base64String = Convert.ToBase64String(imageBytes);
                user.UserPicture = base64String;
            }
        
        StringContent content = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json");

        using (var response = await httpClient.PostAsync("https://localhost:7252/api/Users", content))
        {
            string apiResponse = await response.Content.ReadAsStringAsync();
            receivedUser = JsonConvert.DeserializeObject<User>(apiResponse);
        }
    }
    return View(receivedUser);
}

向我的 model 添加了一个 IFormFile imgfile 属性,并在视图中使用它,如下所示:

<div class="form-group">
                <label asp-for="imgfile" type="file"class="control-label">User Picture</label>
                <input asp-for="imgfile" type="file" class="form-control" />
                <span asp-validation-for="imgfile" class="text-danger"></span>
            </div>

首先,我会将图像类型更改为字符串(可选)

然后在你的 AddUser 方法中添加这个

[BindProperty]
public IFormFile ImageFile { get; set; }
public string Msg { get; set; }  
public static readonly List<string> ImageExtensions = new() { ".JPG", ".BMP", ".PNG" }; //to restrict file extensions


if (HttpContext.Request.Form.Files.Count > 0)// check if the user uploded something
{
     ImageFile = HttpContext.Request.Form.Files.GetFile("file_Main");
     if (ImageFile != null)
     {
          var extension = Path.GetExtension(ImageFile.FileName);//get file name
          if (ImageExtensions.Contains(extension.ToUpperInvariant()))
          {
              using var dataStream = new MemoryStream();
              await ImageFile.CopyToAsync(dataStream);
              byte[] imageBytes = dataStream.ToArray(); // you can save this to your byte array variable and remove the 2 lines below
              string base64String = Convert.ToBase64String(imageBytes);
              User.UserPicture = base64String; // to save the image as base64String 
              }
              else
              {
                  Msg = "image format must be in JPG, BMP or PNG"; //Custom error message
                  return Page();
              }
          }
      }
}

在您看来,只需添加此

@if (Model.User.UserPicture != null)
{
    <img src="data:image/png;base64,@Html.DisplayFor(model => model.User.UserPicture)" height="40" width="40">
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM