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);
    }
    
    
    }
  • 相关阅读:
    mysql配置参数
    nginx配置https,重定向后https变成了http
    网速测试工具
    批量清理mysql进程
    新版本django中的path不能使用正则表达式
    巨好看的xshell配色
    zabbix 基于sendmail发送邮件相关问题
    curl分析请求的各个部分耗时情况
    wqs二分的边界
    oauth2
  • 原文地址:https://www.cnblogs.com/zhang9418hn/p/3173445.html
Copyright © 2011-2022 走看看