Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)) } };
like image 454
chobo2 Avatar asked Oct 15 '22 11:10

chobo2


1 Answers

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!

like image 183
morindo Avatar answered Oct 20 '22 23:10

morindo