LoginSignup
7
8

More than 5 years have passed since last update.

JS: File周りの実装を判別する方法

Last updated at Posted at 2014-08-28

■概要

対象ブラウザにfile関連のAPI実装がなされているか判定を行う方法をまとめた。

■File API が利用できるか判別

クライアントのfileの読み込みやfile情報取得を行うためのAPIが実装されているか確認する。

checkFileAPI
if (window.File) {
    // File APIに関する処理を記述
    config.checkMethod("File APIが実装されてます。");
    return true;
} else {
    config.checkMethod("本ブラウザではFile APIが使えません");
    return false;
}

※上記でFileAPIの実装は確認できるが、versionによって差異があるため下記の様に実際に利用するメソッドやプロパティを含むとより確実となる。

checkAllFileAPI
if (window.File && window.FileReader && window.FileList && window.Blob) {
    // File APIに関する処理を記述
    config.checkMethod("File APIが実装されてます。");
    return true;
} else {
    config.checkMethod("本ブラウザではFile APIが使えません");
    return false;
}

■FormからFileを送信できるか判別

formからfileが選択可能か判別する。iOS6未満ではブラウザのformからファイルをアップロードする事が不可能なので、その判別をする。OSのversionで判別しても良いが、この方が確実且つ、なんのための判別か視認性が向上する。

formTypeFile
var el = document.createElement("input");
el.type = "file";
if(!el.disabled){
    config.checkMethod("Form Fileが実装されてます。");
    return true;
}else{
    config.checkMethod("Form Fileが実装されていません。");
    return false;
}

■ajaxでfileをblob形式・arrayBuffer形式で取得できるか判別

XMLHttpRequest 2 の仕様に含まれる、blob形式もしくはarrayBuffer形式でのfile取得が可能かを判別。
FileAPIやBlobコンストラクタと併せて様々な用途が期待できる。

checkAjaxBlob/arrayBuffer
var xhr = new XMLHttpRequest();
xhr.open('GET', '/', true);
try{
    xhr.responseType = "blob";
    config.checkMethod('XMLHttpRequest に arrayBuffer が実装されています。');
    return true;
}catch(e){
    config.checkMethod('XMLHttpRequest に arrayBuffer が実装されていません。');
    return false;
}

■BlobコンストラクタAPI が利用できるか判別

バイト配列からBlob形式のfileを生成するためのコンストラクタを利用できるか判別。
バイト配列からfileに変換してajaxで投げたり、クライアントに保存したりと様々な用途が期待できる。

checkBlobConstructor
if (window.Blob) {
    config.checkMethod("new Blobが実装されてます。");
    return true;
} else {
    config.checkMethod("本ブラウザではnew Blobが使えません");
    return false;
}

■実装状況

http://caniuse.com/#feat=fileapi
http://caniuse.com/#feat=filereader
http://caniuse.com/#feat=blobbuilder
http://caniuse.com/#feat=xhr2

7
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
8