【问题标题】:how to send uploaded file from javascript to controller in MVC?如何将上传的文件从 javascript 发送到 MVC 中的控制器?
【发布时间】:2013-09-25 05:32:19
【问题描述】:

在我的 MVC 中,我有一个视图,其中包含一个文件上传控件和一个按钮。

 <input type="file" id="Uploadfile" />
 <input type="button" onclick()="GetFile();/>

Javascript函数如下

  function GetFile()
  {
      var file_data = $("#Uploadfile").prop("files")[0];
      window.location.href="Calculation/Final?files="+file_data;
  }

我需要通过文件上传控件将选定的文件传递/发送到 mvc 中的控制器。 我有控制器

public ActionResult Final(HttpPostedFileBase files)
  {
     //here i have got the files value is null.
  }

如何获取选中的文件并发送给控制器? 请帮我解决这个问题。

【问题讨论】:

标签: c# javascript asp.net-mvc asp.net-mvc-3


【解决方案1】:

我在我的项目中提供了类似的功能。 工作代码如下所示:

控制器类

[HttpPost]
public ActionResult UploadFile(YourModel model1)
{
    foreach (string file in Request.Files)
    {
        HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
        if (hpf.ContentLength > 0)
        {
            string folderPath = Server.MapPath("~/ServerFolderPath");
            Directory.CreateDirectory(folderPath);

            string savedFileName = Server.MapPath("~/ServerFolderPath/" + hpf.FileName);
            hpf.SaveAs(savedFileName);
            return Content("File Uploaded Successfully");
        }
        else
        {
            return Content("Invalid File");
        }
        model1.Image = "~/ServerFolderPath/" + hpf.FileName;
    }

    //Refactor the code as per your need
    return View();
}

查看

@using (@Html.BeginForm("UploadFile", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
 <table style="border: solid thin; margin: 10px 10px 10px 10px">
     <tr style="margin-top: 10px">
         <td>
             @Html.Label("Select a File to Upload")
             <br />
             <br />
             <input type="file" name="myfile">
             <input type="submit" value="Upload" />
         </td>
     </tr>
 </table>
}

【讨论】:

    【解决方案2】:

    您不能通过 javascript 发送文件内容(除非 HTMl5)。你做错了。如果你想通过 FileReader api 做基于 HTML5 的解决方案,那么你需要检查一下。 FileReader Api

    只需放一个表单标签,在控制器动作中使用输入的同名即可进行模型绑定

    @using(Html.BeginForm("yourAction","YourControl",FormMethod.Post))
    {
     <input type="file" id="fileUpload" />
    }
    

    然后在控制器中。

    [HTTPPost]
    public ActionResult Final(HttpPostedFileBase fileUpload)
      {
         //here i have got the files value is null.
      }
    

    【讨论】:

      【解决方案3】:

      下面的代码将以隐藏的形式返回完整的帖子,这会产生 ajax 文件上传的错觉。试试看:

      更新:

      JS

      function Upload(sender) {
          var iframe = $("<iframe>").hide();
          var newForm = $("<FORM>");
          newForm.attr({ method: "POST", enctype: "multipart/form-data", action: "/ControllerName/Final" });        
          var $this = $(sender), $clone = $this.clone();
          $this.after($clone).appendTo($(newForm));
          iframe.appendTo($("html")).contents().find('body').html($(newForm));
          newForm.submit();
      }
      

      HTML

      <input type="file" id="Uploadfile" name="Uploadfile" />
      <input type="button" onclick="Upload($('#UploadFile'));"/>
      

      控制器

      public ActionResult Final(HttpPostedFileBase Uploadfile)
      {
           //here you can use uploaded file
      }
      

      【讨论】:

      • 它不调用控制器动作@Jitendra Pancholi
      • @JasperManickaraj:您是否按照我的要求更新了您的 html 并正确复制粘贴了 js?
      • @JasperManickaraj:你一定犯了一些错误,因为我在我的机器上测试了这段代码。
      • 你能给我你的电子邮件地址@Jitendra Pancholi
      【解决方案4】:

      作为 Ravi 回答的补充,我建议使用以下 using 声明:

      @using(Html.BeginForm("yourAction","YourControl",FormMethod.Post, new { enctype="multipart/form-data" }))
      {
         <input type="file" id="fileUpload" />
      }
      

      【讨论】:

        【解决方案5】:

        可以使用json数据查看。

        例如,

        控制器

        public ActionResult Products(string categoryid)
        {
        List<catProducts> lst = bindProducts(categoryid);
        return View(lst);
        }   
        public JsonResult Productsview(string categoryid)
        {
        //write your logic
        var Data = new { ok = true, catid = categoryid};
        return  Json(Data, JsonRequestBehavior.AllowGet);
        }
        

        查看:

        @{
        ViewBag.Title = "Index";
        }
        
        @model ASP.NETMVC.Controllers.Categories
        
        <h2>List Of Categories</h2>
        
        @Html.ListBox("lst_categories", (IEnumerable<SelectListItem>)  ViewBag.Categories)
        
        
        <script type="text/javascript">
        $(function () {
        
        $('#lst_categories').change(function () {
        
        var catid = $('#lst_categories :selected').val();
        
        $.ajax({
        url: '@Url.Action("Productsview", "Jquery")',
        type: 'GET',
        dataType: 'json',
        data: { categoryid: catid },
        cache: false,
        
        success: function (Data) {
        if (Data.ok) {
        
        var link = "@Url.Action("Products", "Jquery", new { categoryid = "catid" })";
        link = link.replace("catid", Data.catid);
        alert(link);
        window.location.href = link;
        }
        }
        });
        });
        });
        </script>
        

        【讨论】:

          猜你喜欢
          • 2013-07-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-12-26
          • 1970-01-01
          • 1970-01-01
          • 2022-08-16
          • 2016-11-24
          相关资源
          最近更新 更多