[英]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.