chobo2
chobo2

Reputation: 85875

How to upload a file through jQuery?

I am wondering how would I do this with like jQuery ajax. Right now I have a jQuery ui dialog box popup and it has an html input file on it.

Now when the user clicks import I want to do an ajax post to the server with jQuery.

I am not sure how to pass the file in though to my action view.

Right now I have it doing a full post back so I have this

<% using (Html.BeginForm("Import", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
{%>
    <br />
    <p><input type="file" id="file" name="file" size="23 accept="text/calendar"></p><br />
    <p><input type="submit" value="Upload file" /></p>        

<% } %> 

Then in my controller

  public ActionResult Import(HttpPostedFileBase file)

So I am not sure how to pass in an HttpPostedFileBase with jQuery and how to set enctype = "multipart/form-data" in jQuery.

Edit

Ok well the jQuery form plugin seems to be the way to go.

$('#frm_ImportCalendar').livequery(function()
{
    var options = {
        dataType: 'json',
        success: function(response)
        {
            alert(response);
        }
    };

    $(this).ajaxForm(options);
});

I was wondering why my json was not working but someone mentioned you can't use it just as is. I am checking out the other link where someone was able to use json.

I am not sure though why in Lck used .submit before the ajax submit method.

Edit

How could I change the file upload json result to return my dictionary array?

        Dictionary<string, string> result = new Dictionary<string, string>();
        result.Add("Msg", "Success!!");
        result.Add("Body", calendarBody);

// how can I change this?
    return new FileUploadJsonResult { Data = new { message = string.Format("{0} uploaded successfully.", System.IO.Path.GetFileName(file.FileName)) } };

Upvotes: 5

Views: 6692

Answers (3)

Alpha Codemonkey
Alpha Codemonkey

Reputation: 3261

I was able to upload a file via AJAX using the jQuery Form plugin and a custom JsonResult class as described here.

Use this to return something like your Dictionary

return new FileUploadJsonResult { Data = new { Msg = "Success!!", Body = calendarBody } };

and to get your message in the callback function

success: function(result) {
  $("#ajaxUploadForm").unblock();
  $("#ajaxUploadForm").resetForm();
  alert(result.Msg);
}

Upvotes: 0

LorenzCK
LorenzCK

Reputation: 7491

As suggested by Dominic, use the jQuery Form plugin. The form you already built should already work correctly. Just add an ID to identify it:

<% using (Html.BeginForm("Import", "Controller", FormMethod.Post, new { id = "asyncForm", enctype = "multipart/form-data" }))

and use jQuery Form to post the data:

$(document).ready(function(){
    $('#asyncForm').submit(function(){
        $(this).ajaxSubmit({
            beforeSubmit: function(){
                //update GUI to signal upload
            }
            data: { additional = 'value' },
            dataType: 'xml',
            success: function(xml){
                //handle successful upload
            }
        });
    });
});

Note that the return dataType in forms that upload files cannot be JSON. Use XML or HTML as response in your controller's method.

Upvotes: 0

morindo
morindo

Reputation: 126

Using the jQuery Form Plugin, you can accomplish an async file upload. Check-out the following link,

jQuery Form Plugin - Code Samples - File Uploads http://jquery.malsup.com/form/#file-upload

Good luck!

Upvotes: 4

Related Questions