我有一个带有输入类型文件的表单。在该输入中,我将仅选择文本文件。
我想知道如何通过JSON / Ajax将所选文件发送到我的操作。
有人已经合作过吗?通过JSON / Ajax发送文件。
我正在使用C#+ MVC 3
这是答案:
http://powerdotnetcore.com/asp-net-mvc/asp-net-mvc-simple-ajax-file-upload-using-jquery
答案 0 :(得分:1)
我不确定你为什么要提到使用JSON但是为了使用Ajax执行文件上传,为什么不使用内置的Ajax表单,因为你使用的是MVC?一个简单的例子可能是这样的:
<强>型号:强>
public class ViewModel
{
[Required, Microsoft.Web.Mvc.FileExtensions(Extensions = "txt", ErrorMessage = "Specify a txt file.")]
public HttpPostedFileBase File { get; set; }
}
查看:强>
<div id="result"></div>
@using (Ajax.BeginForm("Action", "Controller", new AjaxOptions { UpdateTargetId = "result" }, new { enctype="multipart/form-data" } ))
{
@Html.TextBoxFor(m => m.File, new { type = "file" })
@Html.ValidationMessageFor(m => m.File)
}
<强>控制器:强>
[HttpPost]
public ActionResult Action(ViewModel model)
{
if (ModelState.IsValid)
{
// Use your file here
using (MemoryStream memoryStream = new MemoryStream())
{
model.File.InputStream.CopyTo(memoryStream);
}
}
//Return some html back to calling page...
return PartialView("YourPartialView");
}