c# - 如何将上传的文件从javascript发送到MVC中的 Controller ?

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

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

 <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;
  }

我需要通过 fileupload 控件将所选文件传递/发送到 mvc 中的 Controller 。 我有 Controller

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

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

最佳答案

我的项目中有类似的功能要交付。 工作代码看起来像这样:

Controller 类

[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>
}

关于c# - 如何将上传的文件从javascript发送到MVC中的 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18996968/

相关文章:

c# - 使用 LINQ to SQL 进行更新的最有效方式

javascript - 在新 API 的两个单独文件中初始化 Firebase 引用

javascript - Facebook 扩展权限对话框截止 - 不显示允许/禁止按钮

c# - Asp.net单元测试模型数据注解DataType.EmailAddress?

asp.net-mvc - ASP.NET MVC - ModelState.IsValid 为假,如何绕过?

c# - LINQ - 合并 3 个数据集的查询 - 改进

c# - ASP.NET Identity Web Api 2 与 MVC 5 登录 Cookie

c# - 针对 "%"搜索字符串

javascript - 使用 Bootstrap 事件添加动画

javascript - ASP.NET MVC 应用程序最快的网格组件是什么