Skip to main content

Tedshd's Dev note

javascript - file upload

Table of Contents

# javascript - file upload

## Introduction

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

## Skill

  • files API
  • AJAX
  • iframe
  • FormData

## Develop

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

## Issue

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

## Dseign flow

### Attribute

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

### Method

  • upload
  • cancel

### Event

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