【问题标题】:MVC 4 Razor File UploadMVC 4 剃刀文件上传
【发布时间】:2013-03-18 19:40:16
【问题描述】:

我是 MVC 4 的新手,我正在尝试在 我的网站。我找不到错误。我得到一个空值 我的文件中的值。

控制器:

public class UploadController : BaseController
    {
        public ActionResult UploadDocument()
        {
            return View();
        }

       [HttpPost]
       public ActionResult Upload(HttpPostedFileBase file)
       {
           if (file != null && file.ContentLength > 0)
           {
               var fileName = Path.GetFileName(file.FileName);
               var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
               file.SaveAs(path);
           }

           return RedirectToAction("UploadDocument");
        }
    }

查看:

@using (Html.BeginForm("Upload", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ 
    <input type="file" name="FileUpload" />
    <input type="submit" name="Submit" id="Submit" value="Upload" />
}

【问题讨论】:

  • 你只需要改变 public ActionResult Upload(HttpPostedFileBase file)
  • 在这里查看我的实现stackoverflow.com/a/40990080/4251431
  • 错过了表单上的enctype 花了我一个小时
  • Upload() 方法和按钮的连接在哪里。应该有一个 onClick 事件吗?我是 asp.net 新手

标签: asp.net-mvc file-upload


【解决方案1】:

Upload 方法的HttpPostedFileBase 参数必须与file input 同名。

所以只需将输入更改为:

<input type="file" name="file" />

另外,您可以在Request.Files:中找到文件:

[HttpPost]
public ActionResult Upload()
{
     if (Request.Files.Count > 0)
     {
         var file = Request.Files[0];

         if (file != null && file.ContentLength > 0)
         {
            var fileName = Path.GetFileName(file.FileName);
            var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
            file.SaveAs(path);
         }
     }

     return RedirectToAction("UploadDocument");
 }

【讨论】:

  • 如果Request.Files 集合中没有文件,会不会通过Index out of bounds 异常...?
  • 其实它会抛出ArgumentOutOfRangeException,但你是对的,我更新了
  • 请记住,Html.BeginForm 的参数是动作名称和控制器名称(没有“控制器”后缀。例如:Home 而不是 HomeController)。另一个重要的事情是不要在里面包含
    标签,因为是 BeginForm 打开标签
  • 换句话说 - 您的视图模型属性名称必须与输入类型名称匹配。如果您的 viewmodel 属性名为 AgentPhoto,那么您的视图中必须包含以下内容:&lt;input type="file" name="AgentPhoto"/&gt;
  • var path = Path.Combine(Server.MapPath("~/Images/"), fileName);,找不到类“Server”,使用哪个包?
【解决方案2】:

澄清一下。 型号:

public class ContactUsModel
{
    public string FirstName { get; set; }             
    public string LastName { get; set; }              
    public string Email { get; set; }                 
    public string Phone { get; set; }                 
    public HttpPostedFileBase attachment { get; set; }

发布操作

public virtual ActionResult ContactUs(ContactUsModel Model)
{
 if (Model.attachment.HasFile())
 {
   //save the file

   //Send it as an attachment 
    Attachment messageAttachment = new Attachment(Model.attachment.InputStream,       Model.attachment.FileName);
  }
}

最后是检查hasFile的Extension方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AtlanticCMS.Web.Common
{
     public static class ExtensionMethods 
     {
         public static bool HasFile(this HttpPostedFileBase file)
         {
             return file != null && file.ContentLength > 0;
         }        
     }
 }

【讨论】:

  • 公共 HttpPostedFileBase 附件 { 获取;放; }/ 附件不是标识
  • 我认为 Cola 指的是未定义的附件类型。
  • 可以按照 user2028367 的描述使用视图。实际上我忘记在 Html.BeginForm 部分中包含 new { enctype = "multipart/form-data" },因此无法在我的操作中查看文件。很好的答案。 +1 用于在模型类和扩展方法中显示。
  • @BishoyHanna 我如何在我的表格中添加附件。对于其他值,razor 为我们提供了一个简单的语法,但我如何为这个文件做呢?
  • 嗨,@ClintEastwood,该帖子用于上传一个文件,我在网上搜索了与多个上传(为您)匹配的内容,并找到了我认为可行的内容。同样,它的模型基于不使用“Request.Files”stackoverflow.com/questions/36210413/…
【解决方案3】:

查看页面

@using (Html.BeginForm("ActionmethodName", "ControllerName", FormMethod.Post, new { id = "formid" }))
 { 
   <input type="file" name="file" />
   <input type="submit" value="Upload" class="save" id="btnid" />
 }

脚本文件

$(document).on("click", "#btnid", function (event) {
        event.preventDefault();
        var fileOptions = {
            success: res,
            dataType: "json"
        }
        $("#formid").ajaxSubmit(fileOptions);
    });

在控制器中

    [HttpPost]
    public ActionResult UploadFile(HttpPostedFileBase file)
    {

    }

【讨论】:

  • 我同意@Muflix ,这里不需要AJAXHtml.BeginForm 已经完成了这项工作。仅当您不想重定向到 &lt;form action=LINK&gt; 时才需要 AJAX
  • Ajax 更适合较大的文件,因为它可以增强用户体验。
【解决方案4】:

您只需更改输入字段的名称,因为参数和输入字段名称需要相同的名称 只需替换此行您的代码工作正常

 <input type="file" name="file" />

【讨论】:

    【解决方案5】:

    我认为,更好的方法是在控制器或 API 中使用 HttpPostedFileBase。在此之后您可以简单地检测大小、类型等。

    您可以在此处找到文件属性:

    MVC3 How to check if HttpPostedFileBase is an image

    例如ImageApi:

    [HttpPost]
    [Route("api/image")]  
    public ActionResult Index(HttpPostedFileBase file)  
    {  
        if (file != null && file.ContentLength > 0)  
            try 
            {  
                string path = Path.Combine(Server.MapPath("~/Images"),  
                   Path.GetFileName(file.FileName));
    
                file.SaveAs(path);  
                ViewBag.Message = "Your message for success";  
            }  
            catch (Exception ex)  
            {  
                ViewBag.Message = "ERROR:" + ex.Message.ToString();  
            }  
        else 
        {  
            ViewBag.Message = "Please select file";  
        }  
        return View();  
    }
    

    希望对您有所帮助。

    【讨论】:

    • 比什么好? OP 已经在使用HttpPostedFileBase
    猜你喜欢
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-30
    • 1970-01-01
    • 2013-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多