如何将上传的文件从javascript发送到MVC中的控制器? [英] how to send uploaded file from javascript to controller in MVC?

查看:78
本文介绍了如何将上传的文件从javascript发送到MVC中的控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my MVC, i have a view and that contains one file upload control and one button.

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

JavaScript函数如下

Javascript function as follows

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

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

I need to pass/send the selected file via fileupload control to controller in mvc. i have the controller

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

如何获取所选文件并将其发送到控制器? 请帮助我解决此问题.

How to get the selected file and send it to the controller? Plz help me to fix this issue.

推荐答案

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

I had similar functionality to deliver in my project. The working code looks something like this:

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

这篇关于如何将上传的文件从javascript发送到MVC中的控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆