C# 如何将上传的文件从javascript发送到MVC中的控制器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18996968/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:50:43  来源:igfitidea点击:

how to send uploaded file from javascript to controller in MVC?

c#javascriptasp.net-mvcasp.net-mvc-3

提问by Jasper Manickaraj

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

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

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

Javascript function as follows

Javascript函数如下

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

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

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

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.

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

回答by Ravi Gadag

you cannot send file content via javascript (unless HTMl5). and you are doing totally wrong. if you want to do HTML5 based solution via FileReader api then you need to check this out. FileReader Api

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

Just put a form tag and use the same name of the input in the controller action to perform model binding

只需放置一个表单标签并在控制器动作中使用与输入相同的名称来执行模型绑定

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

then in controller.

然后在控制器中。

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

回答by Snake Eyes

As a completion from Ravi's answer, I would suggest to use the following usingstatement:

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

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

回答by Soner Sevinc

You can do it by using json data to view.

您可以通过使用json数据查看来完成。

As instance,

例如,

Controller

控制器

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

View:

看法:

@{
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>

回答by Jitendra Pancholi

Below code will do a full postback in an hidden form which will give an illusion of ajax file upload. Try it

下面的代码将以隐藏的形式执行完整的回发,这会给人一种 ajax 文件上传的错觉。尝试一下

Update:

更新:

JS

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

HTML

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

Controller

控制器

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

回答by Biki

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

我有类似的功能要在我的项目中交付。工作代码如下所示:

Controller Class

控制器类

[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();
}

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