複数Dropzoneのやり方

  1. <html>
  2. <head>
  3. <meta charset="utf-8">
  4. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  5. <script src="js/dropzone.js"></script>
  6. <style>
  7. li.dz {
  8. display: inline-block;
  9. margin:10px;
  10. background-color:#333;
  11. color:#fff;
  12. width:300px;
  13. height:300px;
  14. }
  15. </style>
  16. </head>
  17. <body>
  18. <form action="next.php" method="post" enctype="multipart/form-data">
  19. <input type="hidden" name="file_title">
  20. <input type="hidden" name="file_content">
  21. <input type="hidden" name="file_memo">
  22. <ul>
  23. <li id="dz-title" class="dz" data-name="title">
  24. dropzone
  25. </li>
  26. <li id="dz-content" class="dz" data-name="content">
  27. dropzone
  28. </li>
  29. <li id="dz-memo" class="dz" data-name="memo">
  30. dropzone
  31. </li>
  32. </ul>
  33. </form>
  34. <script>
  35. Dropzone.autoDiscover = false;
  36.  
  37. $('.dz').each(function(i, elem) {
  38. $('#dz-' + $(elem).data('name')).dropzone({
  39. url: 'up.php',
  40. paramName: $(elem).data('name'),
  41. maxFiles: 1,
  42. maxfilesexceeded: function(file) {
  43. alert('アップロードできる画像は' + this.options.maxFiles + 'つです。');
  44. this.removeFile(file);
  45. },
  46. dictMaxFilesExceeded: 'アップロードできる画像は{{maxFiles}}つです。',
  47. success: function(file, result) {
  48. if (result == 'error') {
  49. alert('画像のアップロードに失敗しました。');
  50. this.removeFile(file);
  51. return;
  52. }
  53. $('input[name=file_' + $(elem).data('name') + ']').val(result);
  54. if (file.previewElement) {
  55. return file.previewElement.classList.add('dz-success');
  56. }
  57. },
  58. addRemoveLinks: true,
  59. dictRemoveFile: 'キャンセル',
  60. removedfile: function(file) {
  61. var thisDropzone = this;
  62. var postData = {};
  63.  
  64. $.each($(elem).data(), function(j, data) {
  65. postData[j] = data;
  66. });
  67.  
  68. $.ajax({
  69. url: 'remove.php',
  70. type: 'post',
  71. data: postData,
  72. cache: false,
  73. complete: function() {
  74. $('input[name=file_' + $(elem).data('name') + ']').val('');
  75.  
  76. var _ref;
  77. if (file.previewElement) {
  78. if ((_ref = file.previewElement) != null) {
  79. _ref.parentNode.removeChild(file.previewElement);
  80. }
  81. }
  82.  
  83. return thisDropzone._updateMaxFilesReachedClass();
  84. },
  85. error: function() {
  86. alert('画像の削除に失敗しました。');
  87. }
  88. });
  89. },
  90. });
  91. });
  92. </script>
  93. </body>
  94. </html>

up.php

  1. <?php
  2. if (!isset($_FILES) || count($_FILES) == 0) {
  3. // エラー処理
  4. echo 'error';
  5. exit;
  6. }
  7.  
  8. // アップロード処理
  9.  
  10. $key = key($_FILES);
  11.  
  12. echo $key . '_' . date('Ymd_His') . '.jpg';
  13.  
  14. /*
  15. * 配列で返したい場合は、jsonにエンコードする
  16. $result = [
  17. 'key' => $key,
  18. 'name' => $key . '_' . date('Ymd_His') . '.jpg',
  19. ];
  20.  
  21. echo json_encode($result);
  22. */