1

Basically the below fires right after you click browse and select a file.

I just need a single file upload done of the file the user selects through the regular file input type and I want it to fire right after the file is selected and done asynchronously in the background.

<input type="file" name="imagefile" size="20" />

$('input[type="file"]').change(function () {

    var $file = $(this).val();

    $.ajax({
        url: "/Admin/BannerImageUpload",
        type: 'POST',
        processData: false,
        contentType: false,
        data: { file: $file },
        success: function (data) {
            alert('Load was performed.');
        }


    });

});
LaserBeak
  • 3,257
  • 10
  • 43
  • 73
  • 4
    You're better off [not doing this yourself](http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously-with-jquery#). – Jared Farrish Jun 15 '12 at 05:08
  • Here is what appears to be a simple script, if you're trying to avoid bloat: http://www.jainaewen.com/files/javascript/jquery/iframe-post-form.html – Jared Farrish Jun 15 '12 at 05:10
  • Hmm, I see. HTML5 does allow file uploads using Ajax though so I may look into that. This is for Admin area so backwards compatibility with older browsers is not important. – LaserBeak Jun 15 '12 at 05:12
  • Not to toot my own blog but have you looked into the `FileApi`? http://buildstarted.com/2011/07/17/asp-net-mvc-3-file-uploads-using-the-fileapi/ – Buildstarted Jun 15 '12 at 05:20
  • [BlueImp](https://github.com/blueimp/jQuery-File-Upload/blob/master/js/jquery.fileupload-fp.js#L76) uses a `canvas` to to get the data from the image/file selected. – Jared Farrish Jun 15 '12 at 05:25

1 Answers1

0

You could use the HTML5 File API to asynchronously upload files assuming the client browser supports it. Take a look at the Example: Uploading a user-selected file section towards the end of the documentation I've linked to if you want to see the necessary steps to implement it.

Another possibility is to use an existing ready-to-be-used AJAX file upload component such as Blueimp which implements this functionality. The pros of using such a control is that it will fallback to standard uploading mechanisms if the browser doesn't support HTML5.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928