File.php 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. <?php
  2. namespace Dcat\Admin\Form\Field;
  3. use Dcat\Admin\Contracts\UploadField as UploadFieldInterface;
  4. use Dcat\Admin\Form\Field;
  5. use Dcat\Admin\Form\NestedForm;
  6. use Dcat\Admin\Support\Helper;
  7. use Dcat\Admin\Support\JavaScript;
  8. use Illuminate\Support\Arr;
  9. use Illuminate\Support\Facades\Validator;
  10. use Illuminate\Support\Str;
  11. class File extends Field implements UploadFieldInterface
  12. {
  13. use WebUploader, UploadField;
  14. protected static $css = [
  15. '@webuploader',
  16. ];
  17. protected static $js = [
  18. '@webuploader',
  19. ];
  20. protected $containerId;
  21. /**
  22. * @param string $column
  23. * @param array $arguments
  24. */
  25. public function __construct($column, $arguments = [])
  26. {
  27. parent::__construct($column, $arguments);
  28. $this->setupDefaultOptions();
  29. $this->containerId = $this->generateId();
  30. }
  31. public function setElementName($name)
  32. {
  33. $this->mergeOptions(['elementName' => $name]);
  34. return parent::setElementName($name);
  35. }
  36. /**
  37. * @return mixed
  38. */
  39. public function defaultDirectory()
  40. {
  41. return config('admin.upload.directory.file');
  42. }
  43. /**
  44. * {@inheritdoc}
  45. */
  46. public function getValidator(array $input)
  47. {
  48. if (request()->has(static::FILE_DELETE_FLAG)) {
  49. return false;
  50. }
  51. if ($this->validator) {
  52. return $this->validator->call($this, $input);
  53. }
  54. if (! Arr::has($input, $this->column)) {
  55. return false;
  56. }
  57. $value = Arr::get($input, $this->column);
  58. $value = array_filter(is_array($value) ? $value : explode(',', $value));
  59. $fileLimit = $this->options['fileNumLimit'] ?? 1;
  60. if ($fileLimit < count($value)) {
  61. $this->form->responseValidationMessages(
  62. $this->column,
  63. trans('admin.uploader.max_file_limit', ['attribute' => $this->label, 'max' => $fileLimit])
  64. );
  65. return false;
  66. }
  67. $rules = $attributes = [];
  68. $requiredIf = null;
  69. if (! $this->hasRule('required') && ! $requiredIf = $this->getRule('required_if*')) {
  70. return false;
  71. }
  72. $rules[$this->column] = $requiredIf ?: 'required';
  73. $attributes[$this->column] = $this->label;
  74. return Validator::make($input, $rules, $this->getValidationMessages(), $attributes);
  75. }
  76. /**
  77. * @param string $file
  78. *
  79. * @return mixed|string
  80. */
  81. protected function prepareInputValue($file)
  82. {
  83. if (request()->has(static::FILE_DELETE_FLAG)) {
  84. return $this->destroy();
  85. }
  86. $this->destroyIfChanged($file);
  87. return $file;
  88. }
  89. /**
  90. * @param string|null $relationName
  91. * @param string $relationPrimaryKey
  92. *
  93. * @return $this
  94. */
  95. public function setNestedFormRelation(?string $relationName, $relationPrimaryKey)
  96. {
  97. $this->options['formData']['_relation'] = [$relationName, $relationPrimaryKey];
  98. $this->containerId .= NestedForm::DEFAULT_KEY_NAME;
  99. $this->id .= NestedForm::DEFAULT_KEY_NAME;
  100. return $this;
  101. }
  102. /**
  103. * Set field as disabled.
  104. *
  105. * @return $this
  106. */
  107. public function disable()
  108. {
  109. $this->options['disabled'] = true;
  110. return $this;
  111. }
  112. protected function formatFieldData($data)
  113. {
  114. return Helper::array(Arr::get($data, $this->normalizeColumn()));
  115. }
  116. /**
  117. * @return array
  118. */
  119. protected function initialPreviewConfig()
  120. {
  121. $previews = [];
  122. foreach (Helper::array($this->value()) as $value) {
  123. $previews[] = [
  124. 'id' => $value,
  125. 'path' => basename($value),
  126. 'url' => $this->objectUrl($value),
  127. ];
  128. }
  129. return $previews;
  130. }
  131. protected function forceOptions()
  132. {
  133. $this->options['fileNumLimit'] = 1;
  134. }
  135. /**
  136. * @return string
  137. */
  138. public function render()
  139. {
  140. $this->setDefaultServer();
  141. if (! empty($this->value())) {
  142. $this->setupPreviewOptions();
  143. }
  144. $this->forceOptions();
  145. $this->formatValue();
  146. $this->addScript();
  147. $this->addVariables([
  148. 'fileType' => $this->options['isImage'] ? '' : 'file',
  149. 'containerId' => $this->containerId,
  150. 'showUploadBtn' => ($this->options['autoUpload'] ?? false) ? false : true,
  151. ]);
  152. return parent::render();
  153. }
  154. protected function addScript()
  155. {
  156. $newButton = trans('admin.uploader.add_new_media');
  157. $options = JavaScript::format($this->options);
  158. $this->script = <<<JS
  159. (function () {
  160. var uploader,
  161. newPage,
  162. cID = replaceNestedFormIndex('#{$this->containerId}'),
  163. ID = replaceNestedFormIndex('#{$this->id}'),
  164. options = {$options};
  165. init();
  166. function init() {
  167. var opts = $.extend({
  168. selector: cID,
  169. addFileButton: cID+' .add-file-button',
  170. inputSelector: ID,
  171. }, options);
  172. opts.upload = $.extend({
  173. pick: {
  174. id: cID+' .file-picker',
  175. name: '_file_',
  176. label: '<i class="feather icon-folder"></i>&nbsp; {$newButton}'
  177. },
  178. dnd: cID+' .dnd-area',
  179. paste: cID+' .web-uploader'
  180. }, opts);
  181. uploader = Dcat.Uploader(opts);
  182. uploader.build();
  183. uploader.preview();
  184. function resize() {
  185. setTimeout(function () {
  186. if (! uploader) return;
  187. uploader.refreshButton();
  188. resize();
  189. if (! newPage) {
  190. newPage = 1;
  191. $(document).one('pjax:complete', function () {
  192. uploader = null;
  193. });
  194. }
  195. }, 250);
  196. }
  197. resize();
  198. }
  199. })();
  200. JS;
  201. }
  202. /**
  203. * @return void
  204. */
  205. protected function formatValue()
  206. {
  207. if ($this->value !== null) {
  208. $this->value = implode(',', $this->value);
  209. } elseif (is_array($this->default)) {
  210. $this->default = implode(',', $this->default);
  211. }
  212. }
  213. /**
  214. * @return string
  215. */
  216. protected function generateId()
  217. {
  218. return 'file-'.Str::random(8);
  219. }
  220. }