BootstrapUploadField.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. <?php
  2. namespace Dcat\Admin\Form\Field;
  3. use Dcat\Admin\Form;
  4. use Illuminate\Support\Facades\Storage;
  5. use Illuminate\Support\Facades\URL;
  6. use Symfony\Component\HttpFoundation\File\UploadedFile;
  7. trait BootstrapUploadField
  8. {
  9. /**
  10. * Upload directory.
  11. *
  12. * @var string
  13. */
  14. protected $directory = '';
  15. /**
  16. * File name.
  17. *
  18. * @var null
  19. */
  20. protected $name = null;
  21. /**
  22. * Storage instance.
  23. *
  24. * @var \Illuminate\Filesystem\Filesystem
  25. */
  26. protected $storage;
  27. /**
  28. * If use unique name to store upload file.
  29. *
  30. * @var bool
  31. */
  32. protected $useUniqueName = false;
  33. /**
  34. * If use sequence name to store upload file.
  35. *
  36. * @var bool
  37. */
  38. protected $useSequenceName = false;
  39. /**
  40. * @var bool
  41. */
  42. protected $removable = false;
  43. /**
  44. * Controls the storage permission. Could be 'private' or 'public'.
  45. *
  46. * @var string
  47. */
  48. protected $storagePermission;
  49. /**
  50. * Initialize the storage instance.
  51. *
  52. * @return void.
  53. */
  54. protected function initStorage()
  55. {
  56. $this->disk(config('admin.upload.disk'));
  57. }
  58. /**
  59. * Set default options form image field.
  60. *
  61. * @return void
  62. */
  63. protected function setupDefaultOptions()
  64. {
  65. $defaultOptions = [
  66. 'overwriteInitial' => false,
  67. 'initialPreviewAsData' => true,
  68. 'browseLabel' => trans('admin.browse'),
  69. 'showRemove' => false,
  70. 'showUpload' => false,
  71. 'dropZoneEnabled' => false, //dropzone disabled by default for backward compatibility
  72. // 'initialCaption' => $this->initialCaption($this->value),
  73. 'deleteExtraData' => [
  74. $this->formatName($this->column) => static::FILE_DELETE_FLAG,
  75. static::FILE_DELETE_FLAG => '',
  76. '_token' => csrf_token(),
  77. '_method' => 'PUT',
  78. ],
  79. ];
  80. if ($this->form instanceof Form) {
  81. $defaultOptions['deleteUrl'] = $this->form->getResource().'/'.$this->form->builder()->getResourceId();
  82. }
  83. $this->options($defaultOptions);
  84. }
  85. /**
  86. * Set preview options form image field.
  87. *
  88. * @return void
  89. */
  90. protected function setupPreviewOptions()
  91. {
  92. if (!$this->removable) {
  93. return;
  94. }
  95. $this->options([
  96. //'initialPreview' => $this->preview(),
  97. 'initialPreviewConfig' => $this->initialPreviewConfig(),
  98. ]);
  99. }
  100. /**
  101. * Allow use to remove file.
  102. *
  103. * @return $this
  104. */
  105. public function removable()
  106. {
  107. $this->removable = true;
  108. return $this;
  109. }
  110. /**
  111. * Set options for file-upload plugin.
  112. *
  113. * @param array $options
  114. *
  115. * @return $this
  116. */
  117. public function options($options = [])
  118. {
  119. $this->options = array_merge($options, $this->options);
  120. return $this;
  121. }
  122. /**
  123. * Set disk for storage.
  124. *
  125. * @param string $disk Disks defined in `config/filesystems.php`.
  126. *
  127. * @throws \Exception
  128. *
  129. * @return $this
  130. */
  131. public function disk($disk)
  132. {
  133. try {
  134. $this->storage = Storage::disk($disk);
  135. } catch (\Exception $exception) {
  136. if (!array_key_exists($disk, config('filesystems.disks'))) {
  137. admin_error(
  138. 'Config error.',
  139. "Disk [$disk] not configured, please add a disk config in `config/filesystems.php`."
  140. );
  141. return $this;
  142. }
  143. throw $exception;
  144. }
  145. return $this;
  146. }
  147. /**
  148. * Specify the directory and name for upload file.
  149. *
  150. * @param string $directory
  151. * @param null|string $name
  152. *
  153. * @return $this
  154. */
  155. public function move($directory, $name = null)
  156. {
  157. $this->dir($directory);
  158. $this->name($name);
  159. return $this;
  160. }
  161. /**
  162. * Specify the directory upload file.
  163. *
  164. * @param string $dir
  165. *
  166. * @return $this
  167. */
  168. public function dir($dir)
  169. {
  170. if ($dir) {
  171. $this->directory = $dir;
  172. }
  173. return $this;
  174. }
  175. /**
  176. * Set name of store name.
  177. *
  178. * @param string|callable $name
  179. *
  180. * @return $this
  181. */
  182. public function name($name)
  183. {
  184. if ($name) {
  185. $this->name = $name;
  186. }
  187. return $this;
  188. }
  189. /**
  190. * Use unique name for store upload file.
  191. *
  192. * @return $this
  193. */
  194. public function uniqueName()
  195. {
  196. $this->useUniqueName = true;
  197. return $this;
  198. }
  199. /**
  200. * Use sequence name for store upload file.
  201. *
  202. * @return $this
  203. */
  204. public function sequenceName()
  205. {
  206. $this->useSequenceName = true;
  207. return $this;
  208. }
  209. /**
  210. * Get store name of upload file.
  211. *
  212. * @param UploadedFile $file
  213. *
  214. * @return string
  215. */
  216. protected function getStoreName(UploadedFile $file)
  217. {
  218. if ($this->useUniqueName) {
  219. return $this->generateUniqueName($file);
  220. }
  221. if ($this->useSequenceName) {
  222. return $this->generateSequenceName($file);
  223. }
  224. if ($this->name instanceof \Closure) {
  225. return $this->name->call($this, $file);
  226. }
  227. if (is_string($this->name)) {
  228. return $this->name;
  229. }
  230. return $file->getClientOriginalName();
  231. }
  232. /**
  233. * Get directory for store file.
  234. *
  235. * @return mixed|string
  236. */
  237. public function getDirectory()
  238. {
  239. if ($this->directory instanceof \Closure) {
  240. return call_user_func($this->directory, $this->form);
  241. }
  242. return $this->directory ?: $this->defaultDirectory();
  243. }
  244. /**
  245. * Upload file and delete original file.
  246. *
  247. * @param UploadedFile $file
  248. *
  249. * @return mixed
  250. */
  251. protected function upload(UploadedFile $file)
  252. {
  253. $this->renameIfExists($file);
  254. if (!is_null($this->storagePermission)) {
  255. return $this->storage->putFileAs($this->getDirectory(), $file, $this->name, $this->storagePermission);
  256. }
  257. return $this->storage->putFileAs($this->getDirectory(), $file, $this->name);
  258. }
  259. /**
  260. * If name already exists, rename it.
  261. *
  262. * @param $file
  263. *
  264. * @return void
  265. */
  266. public function renameIfExists(UploadedFile $file)
  267. {
  268. if ($this->storage->exists("{$this->getDirectory()}/$this->name")) {
  269. $this->name = $this->generateUniqueName($file);
  270. }
  271. }
  272. /**
  273. * Get file visit url.
  274. *
  275. * @param $path
  276. *
  277. * @return string
  278. */
  279. public function objectUrl($path)
  280. {
  281. if (URL::isValidUrl($path)) {
  282. return $path;
  283. }
  284. if ($this->storage) {
  285. return $this->storage->url($path);
  286. }
  287. return Storage::disk(config('admin.upload.disk'))->url($path);
  288. }
  289. /**
  290. * Generate a unique name for uploaded file.
  291. *
  292. * @param UploadedFile $file
  293. *
  294. * @return string
  295. */
  296. protected function generateUniqueName(UploadedFile $file)
  297. {
  298. return md5(uniqid()).'.'.$file->getClientOriginalExtension();
  299. }
  300. /**
  301. * Generate a sequence name for uploaded file.
  302. *
  303. * @param UploadedFile $file
  304. *
  305. * @return string
  306. */
  307. protected function generateSequenceName(UploadedFile $file)
  308. {
  309. $index = 1;
  310. $extension = $file->getClientOriginalExtension();
  311. $originalName = $file->getClientOriginalName();
  312. $newName = $originalName.'_'.$index.'.'.$extension;
  313. while ($this->storage->exists("{$this->getDirectory()}/$newName")) {
  314. $index++;
  315. $newName = $originalName.'_'.$index.'.'.$extension;
  316. }
  317. return $newName;
  318. }
  319. /**
  320. * Destroy original files.
  321. *
  322. * @return void.
  323. */
  324. public function destroy()
  325. {
  326. $this->deleteFile($this->original);
  327. }
  328. /**
  329. * Destroy files.
  330. *
  331. * @param $path
  332. */
  333. protected function deleteFile($path)
  334. {
  335. if (!$path) {
  336. return;
  337. }
  338. if ($this->storage->exists($path)) {
  339. $this->storage->delete($path);
  340. } else {
  341. $prefix = $this->storage->url('');
  342. $path = str_replace($prefix, '', $path);
  343. if ($this->storage->exists($path)) {
  344. $this->storage->delete($path);
  345. }
  346. }
  347. }
  348. public function storagePermission($permission)
  349. {
  350. $this->storagePermission = $permission;
  351. return $this;
  352. }
  353. }