BootstrapUploadField.php 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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->getKey();
  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. * Get storage instance.
  149. *
  150. * @return \Illuminate\Filesystem\Filesystem|null
  151. */
  152. public function getStorage()
  153. {
  154. return $this->storage;
  155. }
  156. /**
  157. * Specify the directory and name for upload file.
  158. *
  159. * @param string $directory
  160. * @param null|string $name
  161. *
  162. * @return $this
  163. */
  164. public function move($directory, $name = null)
  165. {
  166. $this->dir($directory);
  167. $this->name($name);
  168. return $this;
  169. }
  170. /**
  171. * Specify the directory upload file.
  172. *
  173. * @param string $dir
  174. *
  175. * @return $this
  176. */
  177. public function dir($dir)
  178. {
  179. if ($dir) {
  180. $this->directory = $dir;
  181. }
  182. return $this;
  183. }
  184. /**
  185. * Set name of store name.
  186. *
  187. * @param string|callable $name
  188. *
  189. * @return $this
  190. */
  191. public function name($name)
  192. {
  193. if ($name) {
  194. $this->name = $name;
  195. }
  196. return $this;
  197. }
  198. /**
  199. * Use unique name for store upload file.
  200. *
  201. * @return $this
  202. */
  203. public function uniqueName()
  204. {
  205. $this->useUniqueName = true;
  206. return $this;
  207. }
  208. /**
  209. * Use sequence name for store upload file.
  210. *
  211. * @return $this
  212. */
  213. public function sequenceName()
  214. {
  215. $this->useSequenceName = true;
  216. return $this;
  217. }
  218. /**
  219. * Get store name of upload file.
  220. *
  221. * @param UploadedFile $file
  222. *
  223. * @return string
  224. */
  225. protected function getStoreName(UploadedFile $file)
  226. {
  227. if ($this->useUniqueName) {
  228. return $this->generateUniqueName($file);
  229. }
  230. if ($this->useSequenceName) {
  231. return $this->generateSequenceName($file);
  232. }
  233. if ($this->name instanceof \Closure) {
  234. return $this->name->call($this, $file);
  235. }
  236. if (is_string($this->name)) {
  237. return $this->name;
  238. }
  239. return $file->getClientOriginalName();
  240. }
  241. /**
  242. * Get directory for store file.
  243. *
  244. * @return mixed|string
  245. */
  246. public function getDirectory()
  247. {
  248. if ($this->directory instanceof \Closure) {
  249. return call_user_func($this->directory, $this->form);
  250. }
  251. return $this->directory ?: $this->defaultDirectory();
  252. }
  253. /**
  254. * Upload file and delete original file.
  255. *
  256. * @param UploadedFile $file
  257. *
  258. * @return mixed
  259. */
  260. protected function upload(UploadedFile $file)
  261. {
  262. $this->renameIfExists($file);
  263. if (! is_null($this->storagePermission)) {
  264. return $this->storage->putFileAs($this->getDirectory(), $file, $this->name, $this->storagePermission);
  265. }
  266. return $this->storage->putFileAs($this->getDirectory(), $file, $this->name);
  267. }
  268. /**
  269. * If name already exists, rename it.
  270. *
  271. * @param $file
  272. *
  273. * @return void
  274. */
  275. public function renameIfExists(UploadedFile $file)
  276. {
  277. if ($this->storage->exists("{$this->getDirectory()}/$this->name")) {
  278. $this->name = $this->generateUniqueName($file);
  279. }
  280. }
  281. /**
  282. * Get file visit url.
  283. *
  284. * @param $path
  285. *
  286. * @return string
  287. */
  288. public function objectUrl($path)
  289. {
  290. if (URL::isValidUrl($path)) {
  291. return $path;
  292. }
  293. if ($this->storage) {
  294. return $this->storage->url($path);
  295. }
  296. return Storage::disk(config('admin.upload.disk'))->url($path);
  297. }
  298. /**
  299. * Generate a unique name for uploaded file.
  300. *
  301. * @param UploadedFile $file
  302. *
  303. * @return string
  304. */
  305. protected function generateUniqueName(UploadedFile $file)
  306. {
  307. return md5(uniqid()).'.'.$file->getClientOriginalExtension();
  308. }
  309. /**
  310. * Generate a sequence name for uploaded file.
  311. *
  312. * @param UploadedFile $file
  313. *
  314. * @return string
  315. */
  316. protected function generateSequenceName(UploadedFile $file)
  317. {
  318. $index = 1;
  319. $extension = $file->getClientOriginalExtension();
  320. $originalName = $file->getClientOriginalName();
  321. $newName = $originalName.'_'.$index.'.'.$extension;
  322. while ($this->storage->exists("{$this->getDirectory()}/$newName")) {
  323. $index++;
  324. $newName = $originalName.'_'.$index.'.'.$extension;
  325. }
  326. return $newName;
  327. }
  328. /**
  329. * Destroy original files.
  330. *
  331. * @return void.
  332. */
  333. public function destroy()
  334. {
  335. $this->deleteFile($this->original);
  336. }
  337. /**
  338. * Destroy files.
  339. *
  340. * @param $path
  341. */
  342. protected function deleteFile($path)
  343. {
  344. if (! $path) {
  345. return;
  346. }
  347. if ($this->storage->exists($path)) {
  348. $this->storage->delete($path);
  349. } else {
  350. $prefix = $this->storage->url('');
  351. $path = str_replace($prefix, '', $path);
  352. if ($this->storage->exists($path)) {
  353. $this->storage->delete($path);
  354. }
  355. }
  356. }
  357. public function storagePermission($permission)
  358. {
  359. $this->storagePermission = $permission;
  360. return $this;
  361. }
  362. }