簡體   English   中英

如何將圖像上傳到asp.net core 2的剃須刀頁面中的磁盤

[英]How to uploade images to disk in asp.net core 2 , razor pages

我是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");
    }

以下是來自的部分:

        <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的專家,我需要向您了解什么是最佳方法。

要將圖像路徑存儲在表中,您需要首先向實體類添加一個屬性,以便它將在表中創建一列。

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接收文件,您需要向IFormFile類型的IFormFile類添加新屬性。

public class CreateModel : PageModel
{
    [BindProperty]
    public Movie Movie { set; get; }

    [BindProperty]
    public IFormFile Image { set; get; }
}

現在在您的表單中,添加類型為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核心中, wwwroot目錄是用於保留靜態資產的特殊目錄。 因此,您可以將圖像保留在該范圍內。 我會在wwwroot內部創建一個名為uploads的子目錄。

要獲取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 ,並將圖像名稱存儲在我們要保存的Movie記錄的ImageName屬性中。 因此,當您要顯示圖像時,請讀取記錄,並使用ImageName屬性並創建url。 (例如:' 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM