保存图像和日期然后显示在页面上的问题

时间:2019-05-05 09:46:26

标签: c# .net core

我想添加新图片,然后在页面上显示为项目列表 所以这是MemyController,方法CreateMemy

在哪里
memyContext db = new memyContext();
// GET: /<controller>/
public IActionResult Index()
{
    var model = db.Memy.ToList();
    return View(model);
}

public string Welcome(string name, string id)
{
    return $"Hello, Your name's {name}. Your ID is {id}.";
}

public IActionResult CreateMeme()
{
    return View();
}

[HttpPost]
public async Task<IActionResult> CreateMeme(Memy model, IFormFile fileUpload)
{

    if (ModelState.IsValid)
    {
        string pathImgMovie = "/images/memy/";
        string pathSave = $"wwwroot{pathImgMovie}";
        if (!Directory.Exists(pathSave))
        {
            Directory.CreateDirectory(pathSave);
        }
        string extFile = Path.GetExtension(fileUpload.FileName);
        string fileName = DateTime.Now.ToString("dd-MM-yyyy-hh-mm-ss") + extFile;
        var path = Path.Combine(Directory.GetCurrentDirectory(), pathSave, fileName);

        using (var stream = new FileStream(path, FileMode.Create))
        {
            await fileUpload.CopyToAsync(stream);
        }

        DateTime dateNow = DateTime.Now;
        model.coverImg = pathImgMovie + fileName;
        model.releaseDate = dateNow;
        model.modifyDate = dateNow;
        db.Memy.Add(model);
        await db.SaveChangesAsync();
        return Redirect("{controller=Home}/{action=Index}/{id?}");
    }
    return View();
}

我要保存图片,并将其添加到文件夹-/images/memy/ model memyContext

public partial class memyContext : DbContext
{
    public memyContext(DbContextOptions<memyContext> options)
          : base(options)
    {

    }
    public memyContext() { }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Server = (localdb)\\mssqllocaldb; Database = memy");
    }

    public DbSet<Memy> Memy { get; set; }
}

Views->Memy->CreateMeme

<h2>CreateMeme</h2>

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div class="form-group">
        @Html.LabelFor(model => model.Title, "Tytuł")
        @Html.TextBoxFor(model => model.Title, new { @class = "form-control", placeholder = "podaj tytul" })
        @Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.releaseDate, "Data dodania")
        <div class='input-group date' id='dtReleaseDate'>
            @Html.TextBoxFor(model => model.releaseDate, new { @class = "form-control", placeholder = "relasedate" })
            @Html.ValidationMessageFor(model => model.releaseDate, "", new { @class = "text-danger" })
            <span class="input-group-addon">
                <span class="glyphicon glyphicon-calendar"></span>
            </span>
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.Category, "Gatunek")
        @Html.DropDownListFor(m => m.Category, new List<SelectListItem>
        {
        new SelectListItem { Text="Śmieszne", Value="Śmieszne" },
        new SelectListItem { Text="Poważne", Value="Poważne" },
        new SelectListItem { Text="Głupie", Value="Głupie" }
        }, "Podaj categorie mema", new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.Category, "", new { @class = "text-danger" })
    </div>

    <div class="form-group">
        @Html.Label("fileCoverImg", "Dodaj")
        <input type="file" id="fileUpload" name="fileUpload" class="form-control" />
        <lable class="text-danger">
            @Html.ValidationMessage("errFileUpload")
        </lable>
    </div>
    <div class=form-group>
        <input onclick="return validateOnSubmit()" type="submit" value="CreateMeme" class="btn btn-primary" />
    </div>
    <div>
        <a asp-controller="Home" asp-action="Index">Back to List</a>
    </div>

}

@section Scripts
    {
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $('#dtReleaseDate').datetimepicker({
                defaultDate: new Date(),
            });
        });
        function validateOnSubmit() {
            if (!$('#fileUpload').val()) {
                $('span[data-valmsg-for="errFileUpload"]').text('The file upload is required.');
            }


            }
        }
    </script>
    <script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.16.0/jquery.validate.min.js"></script>
    <script src="https://ajax.aspnetcdn.com/ajax/jquery.validation.unobtrusive/3.2.6/jquery.validate.unobtrusive.min.js"></script>
}

当我添加一个新的模因时,文件夹images->memy是空的,其中应该有我添加的图像。看来我在MemyController和方法CreateMeme上有问题,但找不到任何错误。该程序未显示任何错误。 这里

string pathImgMovie = "/images/memy/";

string pathSave = $"wwwroot{pathImgMovie}";
if (!Directory.Exists(pathSave))
{
    Directory.CreateDirectory(pathSave);
}

图片应保存在/images/memy/中,但是没有发生,为什么? 我在这里if (ModelState.IsValid) {}处创建了一个断点,并且意识到该if()中的程序别走ModelState有问题吗?

0 个答案:

没有答案