How to upload file using javascript?

This question already has an answer here:

  • How can I upload files asynchronously? 27 answers

  • 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.


    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).

    链接地址: http://www.djcxy.com/p/19620.html

    上一篇: C:\ fakepath \ *。*在Ajax和jQuery中

    下一篇: 如何使用JavaScript上传文件?