-4

我有一个带有输入类型文件的表单。在该输入中,我将仅选择文本文件。

我想知道如何通过 JSON/Ajax 将所选文件发送到我的操作中。

有人已经使用它了吗?通过 JSON/Ajax 发送文件。

我正在使用 C# + MVC 3

这是答案:

http://powerdotnetcore.com/asp-net-mvc/asp-net-mvc-simple-ajax-file-upload-using-jquery

4

1 回答 1

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

}
于 2013-10-09T14:54:01.143 回答