I'm trying to do a simple image uploader for my site.
The idea is to post the image file to the server and the server returns json that contains the URL. Then I use JQuery to update a p tag with the url.
Here is my action method:
[HttpPost]
public JsonResult UploadImage()
{
var image = WebImage.GetImageFromRequest();
var filename = image.FileName;
image.Save(Path.Combine("../Content/Images",filename));
return Json( new{ url= "http://www.example.com/Content/Images/"+filename)} );
}
Here is my view code with script tag. (Jquery is linked in my layout page)
Upload an image
@using (Ajax.BeginForm("UploadImage", "Gtfo", FormMethod.Post, new AjaxOptions
{
HttpMethod = "post",
UpdateTargetId = "filePath",
InsertionMode = InsertionMode.InsertAfter,
OnSuccess = "updateFilePath"
}, new
{
enctype = "multipart/form-data"
}))
{
<input type="file" name="imageUploader" /><br />
<input type="submit" name="Submit" id="Submit" value="Upload" />
}
<script type="text/javascript">
function updateFilePath(result) {
$("#filePath").text(result.url);
}
</script>
The images are uploading and being saved to the server fine. The problem is that once the image is uploaded, the browser redirects to a page displaying the JSON data in plain text.
Edit: I have done some reading around the internet and I thought the problem may be that I have not included the unobtrusive JavaScript on my layout page. I have since added the script to my layout page. Now instead of uploading the image to my server, the server throws an exception at var filename = image.FileName;
. The reason is because image
is now null. This wasn't happening before the inclusion of unobtrusive javascript. I'm not sure if this is a step forward or a step back.