要将图像路径存储在表中,您需要首先向您的实体类添加一个属性,以便它将在您的表中创建一个列。
public class Movie
{
public int ID { get; set; }
public string Title { get; set; }
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
public decimal Price { get; set; }
public string ImageName { set;get;} // This is the new property
}
现在要从 UI 接收文件,您需要向 PageModel 类型的类添加一个新属性IFormFile
public class CreateModel : PageModel
{
[BindProperty]
public Movie Movie { set; get; }
[BindProperty]
public IFormFile Image { set; get; }
}
现在在您的表单中,添加一个类型为 input 的元素file
。确保您的表单标签有一个enctype
属性,并且它的值设置为multipart/form-data
<form method="post" enctype="multipart/form-data">
<div asp-validation-summary="All"></div>
<input type="text" placeholder="Title" asp-for="Movie.Title"/>
<input type="text" placeholder="Genre" asp-for="Movie.Genre" />
<input type="text" placeholder="Price" asp-for="Movie.Price"/>
<input type="file" asp-for="Image"/>
<button type="submit">Save</button>
</form>
现在在您的OnPost
方法中,您可以读取Image
页面模型的属性值并将其保存到磁盘。在 asp.net core 中,该wwwroot
目录是保存静态资产的特殊目录。因此,您可以将图像保留在其下。uploads
我会创建一个名为inside的子目录wwwroot
。
要获取wwwroot
目录的路径,您可以使用IHostingEnvironment
. 因此,将其注入您的页面模型类。
public class CreateModel : PageModel
{
private readonly YourDbContext context;
private readonly IHostingEnvironment hostingEnvironment;
public CreateModel(YourDbContext context,IHostingEnvironment environment)
{
this.hostingEnvironment = environment;
this.context=context;
}
//Your existing code for properties goes here
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
return Page();
if (this.Image != null)
{
var fileName = GetUniqueName(this.Image.FileName);
var uploads = Path.Combine(hostingEnvironment.WebRootPath, "uploads");
var filePath = Path.Combine(uploads,fileName);
this.Image.CopyTo(new FileStream(filePath, FileMode.Create));
this.Movie.ImageName = fileName; // Set the file name
}
context.Movie.Add(this.Movie);
await context.SaveChangesAsync();
return RedirectToPage("MovieList");
}
private string GetUniqueName(string fileName)
{
fileName = Path.GetFileName(fileName);
return Path.GetFileNameWithoutExtension(fileName)
+ "_" + Guid.NewGuid().ToString().Substring(0, 4)
+ Path.GetExtension(fileName);
}
}
这会将文件保存到我们正在保存的记录的属性中wwwroot/uploads
并将图像名称存储在其中。因此,当您要显示图像时,请读取记录,然后使用属性并创建 url。(例如: ' ,其中将来自您的 Movie 记录属性值)ImageName
Movie
ImageName
yourSiteName/uploads/aaa_9521.jpg
aaa_9521.jpg
ImageName
例如,在您的页面模型具有作为实体Movies
集合的属性的另一个页面中,您可以执行此操作Movie
<table>
@foreach (Movie m in Model.Movies)
{
<tr>
<td>@m.Title</td>
<td>@m.Price</td>
<td>
<img src="~/uploads/@m.ImageName"/>
</td>
</tr>
}
</table>