图像文件上传和使用ASP.NET Core 2.0

Ony*_*nyx 6 c# asp.net-core-mvc

在asp.net上完全没有知识,请尝试在这里自学ASP.NET Core 2.0 MVC。

我目前所坚持的是:

尝试找到用于图像上传的教程,以将图像放置到根目录的子目录中,例如/ images / items,然后将该路径保存到数据库中,以便在列出项目时也可以将图像img src。

到目前为止,这是我所做的:

ItemsController:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,SupplierId,CategoryId,Name,Description,Image,Price,Enabled,DateAdded")] Item item)
{
     if (ModelState.IsValid)
     {
         // add image upload


         // end image upload

         _context.Add(item);
         await _context.SaveChangesAsync();
         return RedirectToAction(nameof(Index));
     }
     return View(item);
}
Run Code Online (Sandbox Code Playgroud)

我的ItemModel类是:

public class Item
{
    public int Id { get; set; }
    public int SupplierId { get; set; }
    public int CategoryId { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string Image { get; set; }
    public float Price { get; set; }
    public Boolean Enabled { get; set; }
    public DateTime DateAdded { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我的剃刀Create形式是:

@model QualitySouvenirs.Models.Item

<form asp-action="Create" enctype="multipart/form-data">
    <div asp-validation-summary="ModelOnly" class="text-danger"></div>

    //Other input fields has been removed for brevity

    <div class="form-group">
         <label asp-for="Image" class="control-label"></label>
         <input asp-for="Image"  type="file" class="form-control" />
         <span asp-validation-for="Image" class="text-danger"></span>
    </div>

    <div class="form-group">
        <input type="submit" value="Create" class="btn btn-default" />
    </div>
</form>
Run Code Online (Sandbox Code Playgroud)

这是我Index.cshtml要显示图像的位置:

@model IEnumerable<QualitySouvenirs.Models.Item>

<table class="table">
    <thead>
        <tr>
           // other th's removed for brevity
           <th>
              @Html.DisplayNameFor(model => model.Image)
           </th>

           <th></th>
        </tr>
    </thead>
    <tbody>
       @foreach (var item in Model)
       {
          <tr>
            // other td's removed for brevity
            <td>
               @Html.DisplayFor(modelItem => item.Image)
            </td>

            <td>
               <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
               <a asp-action="Details" asp-route-id="@item.Id">Details</a> |
               <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
            </td>
          </tr>
       }
    </tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

我从这里去哪里?我怀疑我需要一些使用声明吗?

Tan*_*jel 6

编写您的Create POST方法,如下所示:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Item item,IFormFile image)
{
    if (ModelState.IsValid)
    {
        if (image != null && image.Length > 0)
        {
            var fileName = Path.GetFileName(image.FileName);
            var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\images\\items", fileName);
            using (var fileSteam = new FileStream(filePath, FileMode.Create))
            {
                await image.CopyToAsync(fileSteam);
            }
            item.Image = fileName;
        }

        _context.Add(item);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }
    return View(item);
}
Run Code Online (Sandbox Code Playgroud)

然后在表格中显示图像:

<td>
    <img class="img-responsive" src="@Url.Content("~/images/items/" + @item.Image)" alt="">
</td>
Run Code Online (Sandbox Code Playgroud)