【发布时间】:2020-04-25 17:12:33
【问题描述】:
这是我在 ASP.NET CORE 3.0 中的代码,当我使用类型将图像保存为视图模型中的 IFormFile 和模型中的字节时。现在我想在编辑方法中检索这个图像。我无法显示图像。这是我的代码
var formData = new Student()
{
AppUserID = userId,
FirstName = model.FirstName,
MatricMarks = model.MatricMarks,
CollegeName = model.CollegeName,
HSSCMarks = model.HSSCMarks,
};
if (model.Profile != null && model.Profile.FileName != "" && model.Profile.FileName != null)
{
IFormFile file = model.Profile;
if (file.Length > 0)
//Convert Image to byte and save to database
{
using (var stream = new MemoryStream())
{
await file.OpenReadStream().CopyToAsync(stream);
formData.Profile = stream.ToArray();
}
}
}
视图模型
public class StudentSignUpViewModel
{
public string Username { get; set; }
public string CollegeName { get; set; }
public string HSSCMarks { get; set; }
public IFormFile Profile { get; set; }
}
这里是模型类
public string MatricMarks { get; set; }
public string CollegeName { get; set; }
public string HSSCMarks { get; set; }
[Required]
public byte[] Profile { get; set; }
这是我试图显示图像的 Edit[GET] 方法,请指导出了什么问题
public IActionResult Edit(int? id)
{
StudentSignUpViewModel model = new StudentSignUpViewModel();
if (id == null)
{
return NotFound();
}
var student = _context.Students.Where(x => x.StudentId == id.Value).Include(x=>x.AppUser).FirstOrDefault();
model.MatricMarks = student.MatricMarks;
model.CollegeName = student.CollegeName;
model.HSSCMarks = student.HSSCMarks;
model.CoursesArray = student.Courses;
var base64 = Convert.ToBase64String(student.Profile);
ViewBag.imgSrc = string.Format("data:image/jpg;base64,{0}",model.Profile, base64);
}
我试图显示图像的查看方法
<div class="form-group">
<img src="@ViewBag.imgSrc" class="profile-user-img img-responsive img-circle" alt="User profile picture" />
<label asp-for="Username" class="control-label"></label>
<input asp-for="Username" class="form-control" />
注意:不相关的代码被删除。
【问题讨论】:
-
其实这样存储图片不是个好主意,有必要吗?您可以将它们像文件一样保存在项目资源中。阅读此article
标签: asp.net asp.net-core