简体   繁体   English

EF7 MVC ASP.NET文件上传形式

[英]EF7 MVC ASP.NET File upload in form

I'm trying to upload a file alongside with some model information. 我正在尝试上传文件以及一些型号信息。 In my table I already have a field 'image' (string) to save the relative URL to the image. 在我的表格中,我已经有一个字段“ image”(字符串)来将相对URL保存到图像。

But I don't really know how to do the uploading itself. 但是我真的不知道该如何上传。 I've already read a lot off tutorials, but they all use HttpPostedFileBase, which isn't supported anymore? 我已经阅读了很多教程,但是它们都使用了HttpPostedFileBase,现在不再支持它了吗?

This is what I have thus far: 到目前为止,这是我所拥有的:

Upload page: 上传页面:

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

Controller: 控制器:

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

I've added the place where I think the logic should come? 我添加了我认为应该逻辑的地方?

So what I want to do is: 所以我想做的是:

Upload the Image to a folder Rename it Store the relative path as a string to the db. 将图像上传到文件夹重命名将相对路径作为字符串存储到数据库。

Thank you 谢谢

There is no HttpPostedFileBase in MVC6, you have to use IFormFile like this: 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;
}

You can upload images using handlers , link to tutorials are 您可以使用处理程序上传图像,链接到教程是

http://www.c-sharpcorner.com/blogs/uploading-files-using-jquery-ajax-in-asp-net1 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.binaryintellect.net/articles/f2a2f1ee-e18a-416b-893e-883c800f83f4.aspx

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

These tutorials are using jquery to pass the image to the handler and then handler saving the image in the folder. 这些教程使用jquery将图像传递给处理程序,然后处理程序将图像保存在文件夹中。 You can rename the image before uploading to the folder and get back the saved image name in response and then save image name along with other model properties. 您可以在上载到文件夹之前重命名图像,并作为响应返回保存的图像名称,然后将图像名称与其他模型属性一起保存。

I eventually got it working by: 我最终通过以下方式使它起作用:

  1. include using Microsoft.AspNet.Hosting; 包括使用Microsoft.AspNet.Hosting; and using System.IO; using System.Net.Http.Headers; using System.IO; using System.Net.Http.Headers; using System.IO; using System.Net.Http.Headers;
  2. Add public IHostingEnvironment _environment { get; set;} 添加public IHostingEnvironment _environment { get; set;} public IHostingEnvironment _environment { get; set;} to your controller (I added it to my commoncontroller, and then it's available to me on my controller) public IHostingEnvironment _environment { get; set;}添加到您的控制器(我将其添加到我的commoncontroller中,然后就可以在我的控制器上使用它了)
  3. Then in my create: 然后在我的创建中:

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

Just make sure you've created the folder where the images should belong, else it's not going to work without any error! 只要确保您已经创建了图像所属的文件夹,否则它将无法正常使用!

Thanks everybody for your help! 谢谢大家的帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM