coding, photo, plant and demo

*drag and drop

tech btz 20100523 184301
ここ で書いた複数ファイルのdrag and dropは
http://www.appelsiini.net/2009/10/html5-drag-and-drop-multiple-file-upload
を参考にしたのだけど、微妙にmultipartのboundaryの作りが間違っているぽくて、
修正が必要だったのでメモっておく。
PHPではあのまま動くのかもしれないけど、少なくともrubyのcgiじゃだめでした。

修正版は以下。
  1. 1function upload(event) {
  2. 2
  3. 3 var data = event.dataTransfer;
  4. 4
  5. 5 var boundary = '------multipartformboundary' (new Date).getTime();
  6. 6 var dashdash = '--';
  7. 7 var crlf = '\r\n';
  8. 8
  9. 9 /* Build RFC2388 string. */
  10. 10 var builder = '';
  11. 11
  12. 12 var xhr = new XMLHttpRequest();
  13. 13
  14. 14 /* For each dropped file. */
  15. 15 for (var i = 0; i < data.files.length; i ) {
  16. 16 var file = data.files[i];
  17. 17
  18. 18 /* Write boundary. */
  19. 19 builder = dashdash;
  20. 20 builder = boundary;
  21. 21 builder = crlf;
  22. 22
  23. 23 /* Generate headers. */
  24. 24 builder = 'Content-Disposition: form-data; name="user_file"';
  25. 25 if (file.fileName) {
  26. 26 builder = '; filename="' file.fileName '"';
  27. 27 }
  28. 28 builder = crlf;
  29. 29
  30. 30 builder = 'Content-Type: application/octet-stream';
  31. 31 builder = crlf;
  32. 32 builder = crlf;
  33. 33
  34. 34 /* Append binary data. */
  35. 35 builder = file.getAsBinary();
  36. 36 builder = crlf;
  37. 37 }
  38. 38
  39. 39 /* Mark end of the request. */
  40. 40 builder = dashdash;
  41. 41 builder = boundary;
  42. 42 builder = dashdash;
  43. 43 builder = crlf;
  44. 44
  45. 45 xhr.open("POST", "upload.php", true);
  46. 46 xhr.setRequestHeader('content-type', 'multipart/form-data; boundary='
  47. 47 boundary);
  48. 48 xhr.sendAsBinary(builder);
  49. 49
  50. 50 xhr.onload = function(event) {
  51. 51 /* If we got an error display it. */
  52. 52 if (xhr.responseText) {
  53. 53 alert(xhr.responseText);
  54. 54 }
  55. 55 $("#dropzone").load("list.php?random=" (new Date).getTime());
  56. 56 };
  57. 57
  58. 58 /* Prevent FireFox opening the dragged file. */
  59. 59 event.stopPropagation();
  60. 60
  61. 61}

ついでにrubyでは
  1. 1cgi = CGI.new
  2. 2cgi.params["user_file"].each do |file|
  3. 3 do_something(file)
  4. 4end
でok。

そしてこれを貼り付けるために
http://www.nslabs.jp/rb2html.rhtml
を改造して導入してみた。なんか今週末はコードばっかり書いてるなあ。