3

我是 asp.net 框架的初学者,但我真的鼓励学习和应用它。 https://docs.microsoft.com/en-us/aspnet/core/tutorials/razor-pages/razor-pages-start

我跟着它,一切都很好,我通过添加新模型,表格。

假设我们有 Movie 模型:

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 async Task<IActionResult> OnPostAsync()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }

        _context.Movie.Add(Movie);
        await _context.SaveChangesAsync();

        return RedirectToPage("./Index");
    }

以下是 from 的一部分:

        <div class="form-group">
            <label asp-for="Movie.Price" class="control-label"></label>
            <input asp-for="Movie.Price" class="form-control" />
            <span asp-validation-for="Movie.Price" class="text-danger"></span>
        </div>

现在我想在表单中添加一个新字段来上传“封面图片”,以便用户可以浏览并选择电影的封面图片以相同的形式上传。

我的问题是:

  • 我想将文件名存储在数据库中,所以每部电影都有一列“CoverImage”,然后我可以用它来显示或删除。这是好方法吗?

  • 存储文件的最佳位置是什么?在“wwwroot”或其他文件夹中或无关紧要?

  • 上传图片的最佳或最新方法是什么?我应该在上面的三段代码中添加什么?我进行了搜索,发现了许多方法和方法,但是作为 asp.net 的专家,我需要从您那里知道什么是最好的方法。

4

1 回答 1

5

要将图像路径存储在表中,您需要首先向您的实体类添加一个属性,以便它将在您的表中创建一个列。

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 记录属性值)ImageNameMovieImageNameyourSiteName/uploads/aaa_9521.jpgaaa_9521.jpgImageName

例如,在您的页面模型具有作为实体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>
于 2017-11-24T17:33:49.873 回答