zoukankan      html  css  js  c++  java
  • MVC4 图片上传

    新增

    new { enctype = "multipart/form-data" } 这个必须要有
    @using (Html.BeginForm(Html.BeginForm("Create", "UserInfo", FormMethod.Post, new { enctype = "multipart/form-data" })))
    {
    
    <div class="editor-label">
    <span>图片</span>
    </div>
    <div class="editor-field">
    <input type="file" name="filImgs"/>
    @* <input type="hidden" name="ImgUrl" value="@Model.img"/>*@
    
    </div>
    <p>
    <input type="submit" value="上传" />
    </p>
    
    }
    
     
    

      

    [HttpPost]
    public ActionResult Create(UserInfo userinfo)
    {
    var file = Request.Files[0];
    
    var img = //处理图片
    
    userinfo.img = img;
    
    
    try
    {
    if (ModelState.IsValid)
    {
    db.userinfo.Add(userinfo);
    db.SaveChanges();
    return RedirectToAction("Index");
    }
    else
    {
    throw new Exception();
    
    }
    }
    catch (Exception)
    {
    
    return View("Create"); 
    }
    
    }
    
     
    

      

    编辑

    new { enctype = "multipart/form-data" } 这个必须要有
    @using (Html.BeginForm(Html.BeginForm("edit", "UserInfo", FormMethod.Post, new { enctype = "multipart/form-data" })))
    {
    
    <div class="editor-label">
    <span>图片</span>
    </div>
    <div class="editor-field">
    <input type="file" name="filImgs"/>
    @* <input type="hidden" name="ImgUrl" value="@Model.img"/>*@
    
    </div>
    <p>
    <input type="submit" value="修改" />
    </p>
    
    }
    [HttpPost]
    public ActionResult Edit(int id,UserInfo user)
    {
    
    var userinfo = db.userinfo.Find(id);
    //ModelState.IsValid,此处相当于后台验证,防止前台验证因为各种情况被跳过或失效
    try
    {
    bool updateRes = TryUpdateModel(userinfo);//如果字段符合则会赋值,否则保持原有
    
    if (updateRes)
    {
    //图片
    var file = Request.Files[0];
    var img =// 图片处理
    if (img.Length>0)
    {
    userinfo.img = img;
    }
    
    db.SaveChanges();
    return RedirectToAction("Index");
    }
    else
    {
    
    ModelState.AddModelError("", "更新失败!");
    return View(userinfo);
    }
    
    }
    catch (Exception)
    {
    
    return View(userinfo);
    }
    
    
    }
  • 相关阅读:
    CSP-201512
    SCC-Tarjan
    CSP-201509
    Codeforces Round #612 (Div. 2)/A/B/C/D
    CF-Hello 2020/A/B/C
    Anaconda介绍、安装及使用教程
    Linux 新手应该知道的 26 个命令
    Python编码规范:IF中的多行条件
    Python assert 断言函数
    数据结构常见的八大排序算法(详细整理)
  • 原文地址:https://www.cnblogs.com/zhang9418hn/p/3173445.html
Copyright © 2011-2022 走看看