How do I upload files asynchronously?

I want to upload files asynchronously with jQuery.This is my HTML:

<span>File</span>
<input type="file" id="file" name="file" size="10"/>
<input id="uploadbutton" type="button" value="Upload"/>

This is my jQuery code:

$(document).ready(function () {
    $("#uploadbutton").click(function () {
        var filename = $("#file").val();

        $.ajax({
            type: "POST",
            url: "addFile.do",
            enctype: 'multipart/form-data',
            data: {
                file: filename
            },
            success: function () {
                alert("Data Uploaded: ");
            }
        });
    });
});

I only get the file name, not upload the file.What can I do to solve this problem?

#1st floor

I've written this code in the Rails environment .If you use a lightweight jQuery-form plug-in, it only contains five lines of JavaScript.

The challenge is how to make AJAX upload work because the standard remote_form_for does not understand multipart form submissions.It does not send file data that Rails returns with an AJAX request.

This is where the jQuery-form plug-in works.

This is its Rails code:

<% remote_form_for(:image_form, 
                   :url => { :controller => "blogs", :action => :create_asset }, 
                   :html => { :method => :post, 
                              :id => 'uploadForm', :multipart => true }) 
                                                                        do |f| %>
 Upload a file: <%= f.file_field :uploaded_data %>
<% end %>

Here is the relevant JavaScript:

$('#uploadForm input').change(function(){
 $(this).parent().ajaxSubmit({
  beforeSubmit: function(a,f,o) {
   o.dataType = 'json';
  },
  complete: function(XMLHttpRequest, textStatus) {
   // XMLHttpRequest.responseText will contain the URL of the uploaded image.
   // Put it in an image element you create, or do with it what you will.
   // For example, if you have an image elemtn with id "my_image", then
   //  $('#my_image').attr('src', XMLHttpRequest.responseText);
   // Will set that image tag to display the uploaded image.
  },
 });
});

This is what the Rails Controller does. It's beautiful:

 @image = Image.new(params[:image_form])
 @image.save
 render :text => @image.public_filename

I've been using it on Bloggity for the past few weeks and it works like a champion.

#2nd floor

I've been uploading images using the script below, but it works well.

HTML

<input id="file" type="file" name="file"/>
<div id="response"></div>

JavaScript for

jQuery('document').ready(function(){
    var input = document.getElementById("file");
    var formdata = false;
    if (window.FormData) {
        formdata = new FormData();
    }
    input.addEventListener("change", function (evt) {
        var i = 0, len = this.files.length, img, reader, file;

        for ( ; i < len; i++ ) {
            file = this.files[i];

            if (!!file.type.match(/image.*/)) {
                if ( window.FileReader ) {
                    reader = new FileReader();
                    reader.onloadend = function (e) {
                        //showUploadedItem(e.target.result, file.fileName);
                    };
                    reader.readAsDataURL(file);
                }

                if (formdata) {
                    formdata.append("image", file);
                    formdata.append("extra",'extra-data');
                }

                if (formdata) {
                    jQuery('div#response').html('<br /><img src="ajax-loader.gif"/>');

                    jQuery.ajax({
                        url: "upload.php",
                        type: "POST",
                        data: formdata,
                        processData: false,
                        contentType: false,
                        success: function (res) {
                         jQuery('div#response').html("Successfully uploaded");
                        }
                    });
                }
            }
            else
            {
                alert('Not a vaild image!');
            }
        }

    }, false);
});

Explain

I use response div to display the response after the upload and the drive picture are finished.

The best part is that when you use this script, you can send additional data, such as ids, with the file.I have already mentioned extra-data in the script.

At the PHP level, this will work like normal file uploads.Redundant data can be retrieved as $_POST data.

Here, you don't use plug-ins or East West.You can change the code as needed.You're not blindly coding here.This is the core feature of any jQuery file upload.It's actually Javascript.

#3rd floor

You can do this very easily in the original JavaScript.This is an excerpt of my current project:

var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function(e) {
    var percent = (e.position/ e.totalSize);
    // Render a pretty progress bar
};
xhr.onreadystatechange = function(e) {
    if(this.readyState === 4) {
        // Handle file upload complete
    }
};
xhr.open('POST', '/upload', true);
xhr.setRequestHeader('X-FileName',file.name); // Pass the filename along
xhr.send(file);

#4th floor

Note: This answer is obsolete and XHR can now be used to upload files.

You cannot use XMLHttpRequest (Ajax) Upload the file.You can use iframe or Flash to simulate effects.Excellent jQuery Form Plugin , you can publish files through iframe for effect.

#5th floor

Update 2019: It still depends on the browser your demographic uses.

An important thing to understand when using the "new" HTML5 file API is that Not supported until IE 10 It.You may not be able to use older versions of Windows if you have a higher-than-average propensity for a particular market you are targeting.

As of 2017, about 5% of browsers were IE 6, 7, 8, or 9.If you enter a large company (for example, this is a B2B tool, or what you're training for), the number may soar.In 2016, I worked with a company that uses IE8 on more than 60% of its computers.

As of 2019, this edit was almost 11 years away from my original answer.IE9 and lower versions are around 1% globally, but there are still clusters with higher usage.

The most important takeaway feature from this - what tever - is, check the browsers your users use.If you don't, you'll learn a quick and painful lesson about why "working for me" isn't good enough in products delivered to customers. caniuse Is a useful tool, but note where they get demographic information.They may not agree with you.This has never been more true than the corporate environment.

My answers in 2008 are as follows.

However, there are possible non-JS file upload methods.You can create an iframe on the page (hide it using CSS) and then position the form to publish to it.The home page does not need to be moved.

This is a "real" post, so it's not fully interactive.If you need status, you need server-side processing.It depends on your server. ASP.NET There is a better mechanism.PHP normally fails, but you can use Perl Or Apache modifies to fix it.

If you need more than one file to upload, it is best to execute one file at a time (to overcome the maximum file upload limit).Publish the first form to iframe, monitor progress using the above methods, publish the second form to iframe when finished, and so on.

Or use a Java / Flash solution.They can handle their posts more flexibly...

Tags: JQuery Javascript PHP IE

Posted on Sun, 01 Dec 2019 23:12:43 -0800 by nitram