首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >表单中的EF7 MVC ASP.NET文件上载

表单中的EF7 MVC ASP.NET文件上载
EN

Stack Overflow用户
提问于 2015-12-31 18:47:57
回答 3查看 583关注 0票数 0

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

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

这就是我到目前为止所知道的:

上传页面:

代码语言:javascript
复制
@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>
            }

控制器:

代码语言:javascript
复制
 [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);
    }

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

所以我想做的是:

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

谢谢

EN

回答 3

Stack Overflow用户

发布于 2015-12-31 18:58:15

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

代码语言:javascript
复制
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;
}
票数 0
EN

Stack Overflow用户

发布于 2015-12-31 19:05:42

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

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将图像传递给处理程序,然后处理程序将图像保存到文件夹中。您可以在上载到文件夹之前重命名图像,并在响应中取回保存的图像名称,然后将图像名称与其他模型属性一起保存。

票数 0
EN

Stack Overflow用户

发布于 2015-12-31 22:50:24

我最终通过以下方式让它正常工作:

  1. 包括在您的控制器中使用Microsoft.AspNet.Hosting;
    1. (我将其添加到我的通用控制器中,然后我可以在我的创建中的controller)
    2. Then中使用它:

HttpPost public IActionResult Create(LetsViewModel model,IFormFile LetsImages) { LetsViewModel viewModel = null;try { if(!ModelState.IsValid)抛出新异常(“IActionResult模型无效!”);if( targetDirectory != null) { var targetDirectory= Path.Combine(_environment.WebRootPath,string.Format(“LetsImages/uploads”));var fileName = ContentDispositionHeaderValue .Parse(LetsImages.ContentDisposition) .FileName .Trim('"');var savePath = Path.Combine(targetDirectory,fileName);var relPath =“/ContentDispositionHeaderValue/uploads/”+ fileName;尝试{ LetsImages.SaveAs(savePath);model.Lets.Images = relPath;}捕获{抛出新异常(“保存文件时出现问题!”);}} else { model.Lets.Images =空;} model.Lets.UserId = User.GetUserId();model.Lets.StatusId = 1;_kletsContext.Lets.Add(model.Lets);if (_kletsContext.SaveChanges() == 0) {抛出新异常(“无法保存Lets模型!”);} //Success(CreateMessage(ControllerActionType.Create,"klets",model.Name),true);_kletsContext.SaveChanges RedirectToAction(“索引”,“主页”);} catch(Exception ex) { ModelState.AddModelError(string.Empty,“无法保存更改”);viewModel =新建LetsViewModel { Lets = model.Lets,Groups = _kletsContext.Groups.AsEnumerable(),Letses = _kletsContext.Lets.AsEnumerable().OrderBy(m => m.Name) };}返回视图(ViewModel);}

只需确保您已经创建了图像所属的文件夹,否则它将无法正常工作而不会出现任何错误!

感谢大家的帮助!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34545236

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档