EF7 MVC ASP.NET文件以表单形式上载

本文关键字:表单 上载 文件 MVC ASP NET EF7 | 更新日期: 2023-09-27 18:28:32

我正在尝试上传一个文件和一些模型信息。在我的表中,我已经有一个字段"image"(字符串)来保存图像的相对URL。

但我真的不知道如何上传。我已经读了很多教程,但它们都使用了HttpPostedFileBase,现在已经不支持了?

这就是我迄今为止所拥有的:

上传页面:

@using (Html.BeginForm("Lets", "Create", FormMethod.Post, new { @enctype = "multipart/form-data" }))
            {
                @Html.AntiForgeryToken()
                <fieldset>
                    <div class="form-group">
                        <div class="mdl-cell col-md-10 mdl-textfield mdl-js-textfield">
                            @Html.LabelFor(m => m.Lets.Name, new { @class="mdl-textfield__label" })
                            @Html.TextBoxFor(m => m.Lets.Name, new { @class= "form-control mdl-textfield__input" })
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="mdl-cell col-md-10 mdl-textfield mdl-js-textfield">
                            @Html.LabelFor(m => m.Lets.Images)
                            <input type="file" name="LetsImages" id="m.Lets.Images" /> <br />
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="mdl-cell col-md-10 mdl-textfield mdl-js-textfield">
                            @Html.LabelFor(m => m.Lets.Description, new { @class="mdl-textfield__label" })
                            @Html.TextBoxFor(m => m.Lets.Description, new { @class= "form-control mdl-textfield__input" })
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="mdl-cell col-md-10 mdl-textfield mdl-js-textfield">
                            @Html.LabelFor(m => m.Lets.Credits, new { @class="mdl-textfield__label" })
                            @Html.TextBoxFor(m => m.Lets.Credits, new { @class= "form-control mdl-textfield__input" })
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="mdl-cell col-md-10">
                            @Html.LabelFor(m => m.Lets.Group)
                            @Html.DropDownListFor(m => m.Lets.GroupId, new SelectList(Model.Groups, "Id", "Name"), "-- Selecteer een Groep --", new { @class= "form-control" })
                        </div>
                    </div>
                    @Html.ActionLink("Terug naar het overzicht", "Index", new { }, new { @class= "mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect" })
                    <input type="submit" value="Save" class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect" />
                </fieldset>
            }

控制器:

 [HttpGet]
    public IActionResult Create()
    {
        var model = new LetsViewModel
        {
            Lets = new Lets(),
            Groups = _kletsContext.Groups.AsEnumerable(),
            Letses = _kletsContext.Lets.AsEnumerable().OrderBy(m => m.Name)
        };
        return View(model);
    }
    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Create(LetsViewModel model)
    {
        LetsViewModel viewModel = null;
        try
        {
            if(!ModelState.IsValid)
                throw new Exception("The Lets model is not valid!");
                var letsImage = "INSERT LOGIC FOR IMAGEUPLOAD HERE?";
                model.Lets.UserId = User.GetUserId();
                model.Lets.StatusId = 1;
                model.Lets.Images = letsImage;

            _kletsContext.Lets.Add(model.Lets);
            if (_kletsContext.SaveChanges() == 0)
            {
               throw new Exception("The Lets model could not be saved!");
            }   
            //Success(CreateMessage(ControllerActionType.Create, "klets", model.Name), true);
        return RedirectToAction("Index", "Home");
        }
        catch(Exception ex)
        {
            ModelState.AddModelError(string.Empty, "Unable to save changes.");
            viewModel = new LetsViewModel
            {
                Lets = model.Lets,
                Letses = _kletsContext.Lets.AsEnumerable().OrderBy(m => m.Name)
            };
        }
        return View(viewModel);
    }

我添加了我认为逻辑应该出现的地方?

所以我想做的是:

将图像上载到文件夹重命名它将相对路径存储为数据库的字符串。

感谢

EF7 MVC ASP.NET文件以表单形式上载

MVC6中没有HttpPostedFileBase,您必须像这样使用IFormFile

public FileDetails UploadSingle(IFormFile file)
{
    FileDetails fileDetails;
    using (var reader = new StreamReader(file.OpenReadStream()))
    {
        var fileContent = reader.ReadToEnd();
        var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
        fileDetails = new FileDetails
        {
            Filename = parsedContentDisposition.FileName,
            Content = fileContent
        };
    }
    return fileDetails;
}

您可以使用处理程序上传图像,教程链接是

http://www.c-sharpcorner.com/blogs/uploading-files-using-jquery-ajax-in-asp-net1

http://www.binaryintellect.net/articles/f2a2f1ee-e18a-416b-893e-883c800f83f4.aspx

http://www.dotnetjalps.com/2011/12/async-file-upload-with-jquery-and.html?m=1

这些教程使用jquery将图像传递给处理程序,然后处理程序将图像保存在文件夹中。您可以在上传到文件夹之前重命名图像,并返回保存的图像名称作为响应,然后将图像名称与其他模型属性一起保存。

我最终通过使其工作

  1. 包括使用Microsoft.AspNet.Hosting;using System.IO; using System.Net.Http.Headers;
  2. 添加public IHostingEnvironment _environment { get; set;}到您的控制器(我将其添加到我的通用控制器,然后它在我的控制器上对我可用)
  3. 然后在我的创建中:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Create(LetsViewModel model, IFormFile LetsImages)
    {
        LetsViewModel viewModel = null;
        try
        {
            if(!ModelState.IsValid)
                throw new Exception("The Lets model is not valid!");
                if(LetsImages != null)
                {
                        var targetDirectory = Path.Combine(_environment.WebRootPath, string.Format("images/uploads"));
                        var fileName = ContentDispositionHeaderValue
                        .Parse(LetsImages.ContentDisposition)
                        .FileName
                        .Trim('"');
                        var savePath = Path.Combine(targetDirectory, fileName);
                        var relPath = "/images/uploads/" + fileName;
                        try
                        {
                            LetsImages.SaveAs(savePath);
                            model.Lets.Images = relPath;
                        }
                        catch
                        {
                            throw new Exception("There was a problem with saving the file!");
                        }
                }
                else
                {
                    model.Lets.Images = null;
                }
                model.Lets.UserId = User.GetUserId();
                model.Lets.StatusId = 1;
    
            _kletsContext.Lets.Add(model.Lets);
            if (_kletsContext.SaveChanges() == 0)
            {
               throw new Exception("The Lets model could not be saved!");
            }   
            //Success(CreateMessage(ControllerActionType.Create, "klets", model.Name), true);
        return RedirectToAction("Index", "Home");
        }
        catch(Exception ex)
        {
            ModelState.AddModelError(string.Empty, "Unable to save changes.");
            viewModel = new LetsViewModel
            {
                Lets = model.Lets,
                Groups = _kletsContext.Groups.AsEnumerable(),
                Letses = _kletsContext.Lets.AsEnumerable().OrderBy(m => m.Name)
            };
        }
        return View(viewModel);
    }
    

只要确保你已经创建了图像应该属于的文件夹,否则它将无法正常工作而没有任何错误!

感谢大家的帮助!