如何将上传的文件从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>
}