haydnD
haydnD

Reputation: 2293

How to pass a file into controller using jquery

I'm trying to pass a file to my controller using jquery so that the user doesn't have to leave the page after uploading....

I can't seem to get this to work. I keep getting a "null reference" once it passes to my controller. Here's what I've tried:

Controller:

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
var image = Path.GetFileName(file.FileName);

if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var filePath = Path.Combine(Server.MapPath("~/Content/Images/UploadedImages/"), System.IO.Path.GetFileName(file.FileName));
file.SaveAs(filePath);

return Json(filePath.ToString());
}

else
{
return Json("Image failed to load");
}

}

View:

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data", id = "testupload", name = "testupload" }))
{

<div class="editor-field">
<input type="file" name="file" id="file" />
</div>

<input type="submit" value="Submit"/>
}

<input type="button" onclick="upload();" value="Upload" />

<input type="text" id="url"/>

Jquery:

function upload() {

$.post("../../../Home/Upload", $("#testupload"), function (data) {
$("#url").val(data);
});
}

Upvotes: 1

Views: 1672

Answers (1)

Robin Maben
Robin Maben

Reputation: 23114

That cannot be done using ajax.

You need to create a hidden iframe that has a form with the <input type="file" /> field that is submitted to the correct url and you can monitor the result when the form returns.

That way, it would appear seamless.

Upvotes: 1

Related Questions