3
<form method="post" action="#" onsubmit="uploadImage">
    <input type="file" name="imgFile" >
    <input type="submit" id="submit" value="upload">
</form>

How can I upload an image using javascript with ajax call.

4
  • where is your javascript Commented Apr 28, 2015 at 4:43
  • Stack Overflow is not a code writing service. You should review methods to submit a file to a web server, and if you get stuck on a specific problem, ask about it. Commented Apr 28, 2015 at 4:45
  • ok... but only tell me is this possible to upload image using javascript? Commented Apr 28, 2015 at 4:49
  • stackoverflow.com/questions/5587973/javascript-upload-file Commented Apr 28, 2015 at 4:57

2 Answers 2

7

This is just a quick JavaScript solution if you want pure JS.

var file = document.getElementById('id of your input:file').files[0];
var ajax = new XMLHttpRequest;

var formData = new FormData;
formData.append('imagefile', file);

ajax.upload.addEventListener("progress", myProgressHandler, false);
ajax.addEventListener('load', myOnLoadHandler, false);
ajax.open('POST', 'upload.php', true);
ajax.send(formData);

Note: Some sources say that calling Ajax's open method should come after creating an object (before any work with ajax in this case) but me personally never had any troubles using it this way. So it's up to you.

Events:

function myProgressHandler(event) {
  //your code to track upload progress
  var p = Math.floor(event.loaded/event.total*100);
  document.title = p+'%';
}

function myOnLoadHandler(event) {
  // your code on finished upload
  alert (event.target.responseText);
}

You can also add more event handlers such as "error" or "abort". Course, you need to write upload.php to handle uploaded files (PHP is just an example; there are a lot of examples how to do that on SO).

All you need is to make Ajax call on "change" event of your input-file element (upper part of code).

In addition, you can write some featuresCheck function so if user's browser doesn't support something, provide basic file upload instead.

function featuresCheck() {
  var res = window.XMLHttpRequest && window.FormData && window.addEventListener;
  if (res) return true; else return false;
}

/* and test it in your code */
if (featuresCheck()) {
  // use ajax upload
  }
else {
  // use simple file uploader
  }

If you want to use multiple property of file-input you can't use .files[0] (first file selected) and you'll need some loop through files list and do separate uploads for each of them (async of course).

Be aware of security. Do double check of uploaded files before you move them from temp location (check MIME type, extension, rename them).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your code. I am going to apply this.
5

Yes, it is possible, here's very simple code example :

function upload()
{
    var data = new FormData(),
        files = // some <input type="file" />

    data.append('image', files[0]);

    $.ajax({
        url: // Your ajax url, say it's upload.php,
        type: 'post',
        dataType: 'json',
        data: data,
        processData: false,
        contentType: false,
        success: function(image)
        {
            // whatever you want to do 
        }
    });
};

Then in upload.php you need to pick $_POST value and do the upload with move_uploaded_file sort of things.

1 Comment

sorry I have to do it only in javascript or jquery

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.