category: file_upload

javascript - file upload

on 2013-10-20

javascript - file upload


利用 javascript 達到檔案上傳的功能


  • files API
  • AJAX
  • iframe
  • FormData


  • 單純用 javascript
  • 利用 AJAX 上傳
  • 處理 AJAX 上傳在 IE 的問題(利用 iframe 也許可解, Refer)
  • 處理拖拉
  • 處理拖拉資料夾
  • 處理預設樣式


  • FormData
    • AJAX 上傳(IE10 以上)
    • IE 利用 iframe 實作

Dseign flow


  • inputFileNode(input type file element)
  • fileName(name="")
  • server(the file upload to server url)
  • dropArea(set the drop area)


  • upload
  • cancel


Use CustomEvent (IE 9 up) Refer - How to Create Custom Events in JavaScript

  • selectFiles
    • e.fileList (Array)
      • name
      • size
      • type
    • e.length (number)
  • uploadError
  • uploadProgress
    • e.bytesLoaded (number)
    • e.bytesTotal (number)
    • e.percentLoaded (number)
  • uploadComplete
  • dragenter
  • dragover
  • drop
  • drag

develop log

How to do?

Use JavaScript no require any library Use AJAX to upload Must know how to use XMLHttpRequest and use it upload file Use FormData handle ajax upload files, but it only for IE 10 So IE maybe use iframe upload Must easy to use It has many useful method and event Must handle custom event(have cross browser problem) Use File API handle file list, it only for IE10

About code

Use querySelector replace getElementById、getElementsByTagName…etc(IE8 up) document.querySelector Use node method to reduce code

var node;
function node (selector) {
    return document.querySelector(selector);

// use
node('#id'); // html id
node('.class'); // html class
node('div'); // html element

for IE get upload file name

var fileName = document.querySelector('#uploadfile').value.match(/[^\/\\]+$/);

Refer - PHP Error Messages Explained

Read more

file upload show progress bar

on 2013-10-06

file upload show progress bar

If you want show upload progress, you must use AJAX method. And you upload files use FormData object. XMLHttpRequest object has upload properties XMLHttpRequest nsIXMLHttpRequestEventTarget

sample code

xmlHttpRequest.upload.onprogress = function (e) {
    console.log('onprogress', e);
    // progress
    console.log(Math.ceil((e.loaded/ * 100) + '%');