是否可以使用jQuery将文件从文件输入传递给控制器​​?

时间:2013-10-30 22:57:33

标签: jquery asp.net-mvc file-upload httppostedfilebase

我正在尝试将文件作为HttpPostedFileBase传递给我的Controller,因此我可以解析文件并将信息传递回页面。例如,我想允许用户导入vCard,并让它自动填充Contact Creation Form PartialView。

我想通过传入文件,填充我的模型然后返回页面的PartialView来显示在页面上。我试过像下面的jQuery,但我永远不能让我的HttpPostedFileBase正确传递(总是为null)。请记住,我需要在发布后访问文件的InputStream。

var file = "files=" + $("#fileInput").files[0];
$.post("/Contacts/UploadContact/", file, function (returnHtml) {
    alert(returnHtml);
    $("#contactContainer").html(returnHtml);
});

是否可以通过jQuery将文件作为HttpPostedFileBase发布到我的控制器?

2 个答案:

答案 0 :(得分:12)

    Same result can be achieved without `jquery` usage, merely you can use `XMLHttpRequest`
Example:

**Index.cshtml**

    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <script src="@Url.Content("~/Scripts/scripts.js")" ></script>
    <input type="file" id="fileInput" />
    <input type='button' id='go' value="go" />

 $('#fileInput').on("change", function () {      

             var xhr = new XMLHttpRequest();
             var VideofileS = new FormData($('form').get(0));
             xhr.open("POST", "/Contact/UploadContact/");
             xhr.send(VideofileS);
             xhr.addEventListener("load", function (event) {
             alert(event.target.response);
            }, false);
   });   
    });

答案 1 :(得分:0)

非常棒的Ajax上传功能。

如果您有多个文件上传控件,请为其分配不同的ID并执行以下操作以上传所有文件。

fd.append("file1", document.getElementById('fileInput').files[0]);
fd.append("file2", document.getElementById('fileInput').files[1]);
fd.append("file3", document.getElementById('fileInput').files[2]);
fd.append("file4", document.getElementById('fileInput').files[3]);