在我的 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/