Question

I'm attempting to pass a file to my Controller as a HttpPostedFileBase so I can parse through the file and pass information back to the page. For example, I want to allow a user to import a vCard, and have it automatically populate a Contact Creation Form PartialView.

I'd like to do this by passing in the File, populating my model and then return a PartialView of the Form to display on the page. I've attempted jQuery like below, but I can never get my HttpPostedFileBase to pass properly (always null). Keeping in mind that I need to access the InputStream of the file once posted.

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

Is it possible to post a file to my Controller as a HttpPostedFileBase via jQuery?

Was it helpful?

Solution

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

OTHER TIPS

Awesome Ajax upload function.

If you have multiple file upload controls, give them separate IDs and do the following to upload all of them.

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]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top