それマグで!

知識はカップより、マグでゆっくり頂きます。 takuya_1stのブログ

習慣に早くから配慮した者は、 おそらく人生の実りも大きい。

File APIで、input指定ファイルのURLを取得するFormData で送信する

ファイルオブジェクトを返された時に、そこからurl を作るためには

url = window.webkitURL.createObjectURL(file)


chromeさんはwebkitURLを使えよ!ってことでしたね。


でも他のエントリを見ると

http://d.hatena.ne.jp/favril/20100506/1273143063

こっちを使ったほうが楽らしい

reader.readAsDataURL(file)


これで、base64的なimage/data;になる
画像なら、img srcにURLを入れて、高さを固定すれば大体表示できそうです。

$("#pre").attr("src”)
while(reader.readyState!=2){  }

複数ファイルの選択は

ファイルアップロードで複数ファイルを上げるには

 multiple =  "multiple” 

ファイルの送信は FormData を使う

files = $(":file").get(0).files
var fd = new FormData()
for(var i = 0; i< files.length;i++){ fd.append("files", files[i]) }
$.ajax( {type:"POST", url: url, data:data, processData: false, contentType: false} )
FormData についてはこういうことになっている
[Constructor]
interface FormData {
  void append(DOMString name, Blob value);
  void append(DOMString name, DOMString value);
};

FormDataは appendで String か Blobを取る。

Blobとはつまり、Fileのことである。


FormData を使うために XmlHttpRequestの send()を見てみると

interface XMLHttpRequest : XMLHttpRequestEventTarget {
  //略
  void send();
  void send(Blob data);
  void send(Document data);
  void send([AllowAny] DOMString? data);
  void send(FormData data);
  void abort();
  //略
};

send()の引数には Blog(file)やDocument,文字列 FormDataがとれることがわかる。

Formdataは {Blob,Sting,Dom}で構成された群であり
それぞれの部分群が blob,file,string などになる。

でもって、それぞれの場合の処理フローはW3Cに出ている

↪If data is a Blob

If the object is of type File and its mediaType attribute is not the empty string let mime type be its value.

Let the request entity body be the raw data represented by data.
↪If data is a Document

Let encoding be the preferred MIME name of the character encoding of data. If encoding is UTF-16 change it to UTF-8.

Let mime type be "application/xml" or "text/html" if Document is flagged as HTML document, followed by ";charset=", followed by encoding.

Let the request entity body be the result of getting the innerHTML attribute on data converted to Unicode and encoded as encoding. Re-raise any exception this raises.

Note: In particular, if the document cannot be serialized an INVALID_STATE_ERR exception is raised.

Note: Subsequent changes to the Document have no effect on what is submitted.
↪If data is a DOMString

Let encoding be UTF-8.

Let mime type be "text/plain;charset=UTF-8".

Let the request entity body be data converted to Unicode and encoded as UTF-8.
↪If data is a FormData

Let mime type be "multipart/form-data".

Let the request entity body be the result of running the multipart/form-data encoding algorithm with data as form data set.

http://www.w3.org/TR/2010/WD-XMLHttpRequest2-20100907/#dom-xmlhttprequest-send
|

そう、FormDataを、XmlHttpに渡したときは multipart/form-data が content-typeに設定されるんですね。


その他のやり方

http://havelog.ayumusato.com/develop/javascript/e171-ajax-file-upload.html
いまさら iFrameもないわー

ファイルAPI活用しましょう