Skip to content Skip to sidebar Skip to footer

Issue With AJAX Upload Script In Mvc

I found this ajax file upload script here http://www.phpletter.com/Demo/AjaxFileUpload-Demo/ Which is supposed to add ajax functionality to my file upload form

Solution 1:

The plugin you are using expects text/html as response Content Type even if you are passing JSON. So if you really want to use it you need to do this:

return Content("{ FileName: '/Uploads/' }", "text/html");

As you understand that's crap.

So go ahead and download the jquery form plugin. It's much easier to use. You don't have to do anything in your HTML, it's totally unobtrusive. Just leave the form as is and in javascript simply:

$(function() {
    // Only indicate the form id, it will take care of reading the form action, 
    // returning false, ..., all you need is to concentrate 
    // on the success callback
    $('#uploadForm').ajaxForm(function(result) {
        alert(result);
    });
});

Also notice that in case of error you shouldn't return Javascript. You always need to return Json from your controller action. So in case of error:

return Json(new { errorMessage = "Kaboom", fileName = "" });

and in case of success:

return Json(new { errorMessage = "", fileName = "/Uploads/" + file.FileName });

so now you can check whether there's an error by inspecting the errorMessage property on the returned JSON object:

$('#uploadForm').ajaxForm(function(result) {
    if (result.errorMessage != '') {
        alert(result.errorMessage);
    } else {
        $('#RelatedFileName').val(result.fileName);
        $('#dialog').dialog('close');
    }
});

Solution 2:

If you want to do ajax uploads, you are going to want do the upload form inside an iframe.

See: http://www.ajaxf1.com/tutorial/ajax-file-upload-tutorial.html


Solution 3:

It's possible to set the content type here as well:

return Json(new { FileName = "/Uploads/filename.ext" }, "text/html", JsonRequestBehavior.AllowGet);

Post a Comment for "Issue With AJAX Upload Script In Mvc"