MVC 4 Razor文件上传

244 asp.net-mvc file-upload

我是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");
        }
    }
Run Code Online (Sandbox Code Playgroud)

视图:

@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" />
}
Run Code Online (Sandbox Code Playgroud)

Cri*_*ufu 323

Upload方法的HttpPostedFileBase参数必须具有相同的名称的file input.

所以只需将输入更改为:

<input type="file" name="file" />
Run Code Online (Sandbox Code Playgroud)

此外,您可以在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");
 }
Run Code Online (Sandbox Code Playgroud)

  • 换句话说 - 您的视图模型属性名称必须与输入类型名称的名称匹配.如果你的`viewmodel`属性被命名为`AgentPhoto`,那么你的视图上必须有以下内容:`<input type ="file"name ="AgentPhoto"/>` (5认同)
  • 如果`Request.Files`集合中没有文件,它不会通过`Index out of bounds`异常吗? (2认同)
  • 实际上它会抛出`ArgumentOutOfRangeException`,但你是对的,我更新了 (2认同)
  • 请记住,Html.BeginForm的参数是动作名称和控制器名称(没有'controller'后缀.例如:Home而不是HomeController).另一个重要的事情是不在里面包含<form>标签,因为是打开标签的BeginForm (2认同)

Bis*_*nna 65

澄清它.模型:

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; }
Run Code Online (Sandbox Code Playgroud)

发布行动

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

最后用于检查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;
         }        
     }
 }
Run Code Online (Sandbox Code Playgroud)

  • 可以如user2028367所描述的那样使用视图.实际上我忘了在Html.BeginForm部分中包含新的{enctype ="multipart/form-data"},因此无法在我的操作中查看该文件.很好的答案.在Model类和Extension方法中显示+1. (2认同)

Jag*_*B S 18

查看页面

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

脚本文件

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

在控制器中

    [HttpPost]
    public ActionResult UploadFile(HttpPostedFileBase file)
    {

    }
Run Code Online (Sandbox Code Playgroud)

  • 我同意@Muflix,你在这里不需要`AJAX`.`Html.BeginForm`已经完成了这项工作.只有在你不想重定向到`<form action = LINK>`时才需要AJAX (2认同)

Haf*_*sad 6

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

 <input type="file" name="file" />
Run Code Online (Sandbox Code Playgroud)