File.php
10.0 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
<?php
/**
* +-----------------------------------------------------------------------------------------------------------------------
* 重写 laravel-admin Form\Field\File 类
* +-----------------------------------------------------------------------------------------------------------------------
*
* PHP version 7
*
* @category App\Admin\Rewrite\Form\Field
* @package App\Admin\Rewrite\Form\Field
* @author Richer <yangzi1028@163.com>
* @date 2020年11月12日13:49:31
* @copyright 2020-2022 Richer (http://www.Richer.com/)
* @license http://www.Richer.com/ License
* @link http://www.Richer.com/
*/
namespace App\Admin\Rewrite\Form\Field;
use Encore\Admin\Form\Field;
use Encore\Admin\Form\Field\File as Base;
use Illuminate\Support\Arr;
use Symfony\Component\HttpFoundation\File\UploadedFile;
/**
* Class File
*
* @category App\Admin\Rewrite\Form\Field
* @package App\Admin\Rewrite\Form\Field
* @author Richer <yangzi1028@163.com>
* @date 2020年11月12日13:49:31
* @copyright 2020-2022 Richer (http://www.Richer.com/)
* @license http://www.Richer.com/ License
* @link http://www.Richer.com/
*/
class File extends Field
{
use UploadField;
/**
* Css.
*
* @var array
*/
protected static $css = [
'/vendor/laravel-admin/bootstrap-fileinput/css/fileinput.min.css?v=4.5.2',
];
/**
* Js.
*
* @var array
*/
protected static $js = [
'/vendor/laravel-admin/bootstrap-fileinput/js/plugins/canvas-to-blob.min.js',
'/vendor/laravel-admin/bootstrap-fileinput/js/fileinput.min.js?v=4.5.2',
];
/**
* Create a new File instance.
*
* @param string $column
* @param array $arguments
*/
public function __construct($column, $arguments = [])
{
$this->initStorage();
parent::__construct($column, $arguments);
}
/**
* Default directory for file to upload.
*
* @return mixed
*/
public function defaultDirectory()
{
return config('admin.upload.directory.file');
}
/**
* {@inheritdoc}
*/
public function getValidator(array $input)
{
if (request()->has(static::FILE_DELETE_FLAG)) {
return false;
}
if ($this->validator) {
return $this->validator->call($this, $input);
}
/*
* If has original value, means the form is in edit mode,
* then remove required rule from rules.
*/
if ($this->original()) {
$this->removeRule('required');
}
/*
* Make input data validatable if the column data is `null`.
*/
if (Arr::has($input, $this->column) && is_null(Arr::get($input, $this->column))) {
$input[$this->column] = '';
}
$rules = $attributes = [];
if (!$fieldRules = $this->getRules()) {
return false;
}
$rules[$this->column] = $fieldRules;
$attributes[$this->column] = $this->label;
return \validator($input, $rules, $this->getValidationMessages(), $attributes);
}
/**
* Prepare for saving.
*
* @param UploadedFile|array $file
*
* @return mixed|string
*/
public function prepare($file)
{
if (request()->has(static::FILE_DELETE_FLAG)) {
return $this->destroy();
}
$this->name = $this->getStoreName($file);
return $this->uploadAndDeleteOriginal($file);
}
/**
* Upload file and delete original file.
*
* @param UploadedFile $file
*
* @return mixed
*/
protected function uploadAndDeleteOriginal(UploadedFile $file)
{
$this->renameIfExists($file);
$path = null;
if (!is_null($this->storagePermission)) {
$path = $this->storage->putFileAs($this->getDirectory(), $file, $this->name, $this->storagePermission);
} else {
$path = $this->storage->putFileAs($this->getDirectory(), $file, $this->name);
}
$this->destroy();
return $path;
}
/**
* Preview html for file-upload plugin.
*
* @return string
*/
protected function preview()
{
return $this->objectUrl($this->value);
}
/**
* Initialize the caption.
*
* @param string $caption
*
* @return string
*/
protected function initialCaption($caption)
{
return basename($caption);
}
/**
* @return array
*/
protected function initialPreviewConfig()
{
$config = ['caption' => basename($this->value), 'key' => 0];
$config = array_merge($config, $this->guessPreviewType($this->value));
return [$config];
}
/**
* @param string $options
*/
protected function setupScripts($options)
{
// add by Richer 是否自动上传
$auto_upload = Arr::get(obj_2_array(json_decode($options)), 'auto_upload', 0);
$this->script = <<<EOT
$("input{$this->getElementClassSelector()}").fileinput({$options});
EOT;
if ($this->fileActionSettings['showRemove']) {
$text = [
'title' => trans('admin.delete_confirm'),
'confirm' => trans('admin.confirm'),
'cancel' => trans('admin.cancel'),
];
$this->script .= <<<EOT
$("input{$this->getElementClassSelector()}").on('filebeforedelete', function() {
return new Promise(function(resolve, reject) {
var remove = resolve;
swal({
title: "{$text['title']}",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "{$text['confirm']}",
showLoaderOnConfirm: true,
cancelButtonText: "{$text['cancel']}",
preConfirm: function() {
return new Promise(function(resolve) {
resolve(remove());
});
}
});
});
})// 选择文件后处理事件
.on("filebatchselected", function(e, files) {
// TODO
if ($(".kv-fileinput-error.file-error-message").is(":hidden")){
// 清除当前的预览图 ,并隐藏 【移除】 按钮
// $(this).fileinput('clear').fileinput('unlock')
// 文件选择完直接调用上传方法。
// TODO
console.log("auto_upload: $auto_upload");
if ($auto_upload==1) {
$(this).fileinput("upload");
}
}
})// 上传前
.on('filepreupload', function(event, data, previewId, index) {
$(this).fileinput('clear').fileinput('unlock')
})
// 异步上传成功结果处理
.on('fileuploaded', function(event, data, previewId, index) {
// console.log("异步");
// 上传成功后的样式 file-preview-success
var obj = $(".file-preview-success").eq(index);
// 设置图片的路径
obj.find(".kv-file-content").find("img").attr("src",data.response.data[0].full_path);
})
//异步上传失败结果处理
.on('fileerror', function (event, data, msg) {
// console.log(event, data, msg);
//alert(msg)
})
//异步上传失败结果处理
.on('fileuploaderror', function (event, data, msg) {
//console.log(msg);
// console.log(event, data, msg);
//alert(msg);
// if (msg != '无效的文件上传.') {
// // swal_error(msg)
// $(".kv-fileinput-error.file-error-message").find("li").text(msg);
// }
//
//
})
.on('filebatchuploaderror', function(event, data, msg) {
// alert();
})
// 同步上传回调
.on('filebatchuploadsuccess', function(event,data,previewId,index) {
// console.log(event);
// console.log(data);
// console.log(previewId);
// console.log(index);
// console.log($(".file-preview-frame"));
// console.log($(".file-preview-success"));
var response_data = data.response.data;
console.log(response_data);
var full_path = response_data.full_path;
var original_name = response_data.original_name;
// 设置图片的路径
$(".file-uploading").find(".kv-file-content").find("img").attr("src",full_path).attr("original_name", original_name).addClass('full-path');
// console.log( $(this).find(".kv-file-content").find("object"));
// 设置文件路径和件原始文件名
$(".file-uploading").find(".kv-file-content").find("object").attr("src",full_path).attr("original_name", original_name).addClass('full-path');
// $(".file-preview-frame.krajee-default.kv-preview-thumb").each(function (i,e) {
// // console.log(response_data[i].full_path);
// //console.log( $(this).parent().html());
// });
// 上传成功后的样式 file-preview-success
$("div[id^='uploaded-']").each(function (i,e) {
});
});
EOT;
}
if ($this->fileActionSettings['showDrag']) {
$this->addVariables([
'sortable' => true,
'sort_flag' => static::FILE_SORT_FLAG,
]);
$this->script .= <<<EOT
$("input{$this->getElementClassSelector()}").on('filesorted', function(event, params) {
var order = [];
params.stack.forEach(function (item) {
order.push(item.key);
});
$("input{$this->getElementClassSelector()}_sort").val(order);
});
EOT;
}
}
/**
* Render file upload field.
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function render()
{
$this->options(['overwriteInitial' => true, 'msgPlaceholder' => trans('admin.choose_file')]);
$this->setupDefaultOptions();
if (!empty($this->value)) {
$this->attribute('data-initial-preview', $this->preview());
$this->attribute('data-initial-caption', $this->initialCaption($this->value));
$this->setupPreviewOptions();
/*
* If has original value, means the form is in edit mode,
* then remove required rule from rules.
*/
unset($this->attributes['required']);
}
$options = json_encode_options($this->options);
$this->setupScripts($options);
return parent::render();
}
}