[英]ASP.NET Core how to upload image to SQL Server database?
I am trying to do a simple app to register users to a database with name, surname, profile photo etc. then edit or delete them.我正在尝试做一个简单的应用程序来将用户注册到具有姓名、个人资料照片等的数据库,然后编辑或删除它们。 I am planning to upload the image as
IFileForm
, then convert it to varbinary
for SQL Server.我打算将图像上传为
IFileForm
,然后将其转换为 SQL 服务器的varbinary
。 But I am having a problem on how to implement uploading the image.但是我在如何实现上传图片方面遇到了问题。 The code works for other members.
该代码适用于其他成员。 Any help would be appreciated.
任何帮助,将不胜感激。
My user model class for API我的用户 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; };
}
Post method for my API我的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);
}
My user model for Web App我的用户 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; }
}
Post method for Web App to consume API 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);
}
And finally the view for AddUser.最后是 AddUser 的视图。 Removed the code for other members because too long.
删除了其他成员的代码,因为太长了。
<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>
EDIT: I managed to make it work after editing vega_gf's answer a little.编辑:稍微编辑一下 vega_gf 的答案后,我设法让它工作。 I am pretty sure it is not the most optimal way but it works for now.
我很确定这不是最佳方式,但现在可以使用。
My AddUser method now:我现在的 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);
}
Added an IFormFile imgfile property to my model and used it in view like this:向我的 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>
First I would change image type to string(optional)首先,我会将图像类型更改为字符串(可选)
Then on your AddUser method you add this然后在你的 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();
}
}
}
}
on your view just add this在您看来,只需添加此
@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.