在asp mvc中以注册形式上传图片

时间:2016-07-04 12:53:22

标签: asp.net asp.net-mvc image-uploading

我想将我的模型保存在数据库中并将我的图片上传到服务器我希望在点击保存按钮时完成所有操作

我的观点模型是:

public class PostViewModel
{
    public int PostId { get; set; }

    [Required]
    [StringLength(255)]
    public String Address { get; set; }

    [Required]
    [StringLength(255)]
    [Display(Name = "title")]
    public string PostTitle { get; set; }

    [Required]
    [Display(Name = "full text")]
    public string PostContent { get; set; }

    [StringLength(30)]
    [Display(Name = "Image")]
    public string PostImage { get; set; }

    [Display(Name = "Date")]
    public DateTime CreatedAt { get; set; }

    public virtual IList<TagCheckBox> TagList { get; set; }

}

和Create.cshtml:

@model First.Areas.Admin.ViewModels.PostViewModel
@using (Html.BeginForm("Create", "Posts", FormMethod.Post, new { enctype = "multipart/form-data" }))   {   @Html.AntiForgeryToken()    
<div class="row">
    <div class="col-lg-8">
        <div class="form-horizontal">

            @Html.ValidationSummary(true, "", new { @class = "text-danger" })

            <div class="form-group">
                @Html.LabelFor(model => model.PostTitle, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.TextBoxFor(model => model.PostTitle, new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.PostTitle, "", new { @class = "text-danger" })
                </div>
            </div>
            <div class="form-group">
                @Html.LabelFor(model => model.Address, "لینک ", htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.TextBoxFor(model => model.Address, new { @class = "form-control", data_slug = "#PostTitle" })
                    @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.PostContent, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.TextAreaFor(model => model.PostContent, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.PostContent, "", new { @class = "text-danger" })
                </div>
            </div>
            <div class="form-group">
                @Html.LabelFor(model => model.PostImage, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                  <input type="file" name="fileUpload" />
                    @Html.ValidationMessageFor(model => model.PostImage, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="save" class="btn btn-primary" />
                </div>
            </div>
        </div>
    </div>

和控制器:

public async Task<ActionResult> Create([Bind(Include = "PostId,Address,PostTitle,PostContent,PostImage,TagList")] PostViewModel postViewModel,HttpPostedFileBase file)
    {
        if (ModelState.IsValid)
        {
            string fileName = "1.jpg";
            if (file != null && file.ContentLength > 0)
            {
                fileName = Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath("~/Content/images/blog"), fileName);
                file.SaveAs(path);
            }
            else
            {
                return View(postViewModel);
            }
            var selectedTags = ReconsileTags(postViewModel.TagList);

            Post post = new Post
            {
                PostTitle = postViewModel.PostTitle,
                PostContent = postViewModel.PostContent,

                Address = postViewModel.Address,
                Tags = selectedTags
            };
            post.PostImage = fileName ;
            post.AuthorId = User.Identity.GetUserId();

            db.Posts.Add(post);
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }

文件(HttpPostedFileBase)为空! 请帮我解决这个问题。 (我是asp mvc中的新手)

2 个答案:

答案 0 :(得分:1)

不是传递HttpPostedFileBase参数,而是删除它并执行以下操作:

HttpFileCollectionBase fileCollection = Request.Files;
if(fileCollection.Count > 0)
{
    foreach(var file in fileCollection)
    {
        // do something with HttpPostedFileBase object
    }
}

答案 1 :(得分:1)

我将<input name="fileUpload"/>更改为<input name="file"/>并且效果很好 感谢@KartikeyaKhosla的帮助