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

时间:2018-09-19 05:59:09

标签: c# asp.net-core-mvc

asp.net上的总体菜鸟,试图在这里自学ASP.NET Core 2.0 MVC。

我目前所坚持的:

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

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

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);
}

我的Item模型班是:

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; }
}

我的剃须刀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>

这是我的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>

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

1 个答案:

答案 0 :(得分:5)

编写您的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);
}

然后在表格中显示图像:

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