laravel-admin文件上传及处理

  • file表单通过move指定上传目录
  • saving保存回调设置文件名及文件校验参数
  • saved保存回调实现后期处理,如文件重命名等
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$form->hidden('file_name', '更新文件名');
$form->file('file_path', '更新文件')->move(function ($file_path) use ($form) {
if (!empty($form->app_id)) {
Log::info('Move App ID: '. $form->app_id);
$app = AndroidApp::where('id', $form->app_id)->get(['name'])->first();
Session::put('app', $app);
} else {
$app = Session::get('app');
}
return 'files/' . $app->name;
});

$form->hidden('size', 'Size');
$form->hidden('md5', 'Md5');
$form->hidden('sha1', 'Sha1');
1
2
3
4
5
6
7
8
9
10
11
12
13
14
$form->saving(function ($form) {
$file = $form->file_path;
if ($file != null && $file->isValid()) {
Log::info('App Id: ' . $form->app_id);
Log::info('Temp File: ' . $file);
Log::info('Original Name: ' . $file->getClientOriginalName());
$file_name = $file->getClientOriginalName();

$form->file_name = $file_name;
$form->size = filesize($file);
$form->md5 = md5_file($file);
$form->sha1 = sha1_file($file);
}
});
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
$form->saved(function ($form) {
$app_version = $form->model();

//$app = AndroidApp::where('id', $app_version->app_id)->get(['name'])->first();
$app = $app_version->app;
Session::put('app', $app);

if ($form->file_path != null && $form->file_path->isValid()) {
$extension = substr($form->file_name, strrpos($form->file_name, '.') + 1);
if ($extension === 'apk' || $extension === 'patch' || $extension === 'tpatch') {
$extension = 'zip';
}
$file_name = substr($form->file_name, 0, strrpos($form->file_name, '.') + 1) . $extension;

$old_file = public_path('upload/') . $app_version->file_path;
$new_file = public_path('upload/files/') . $app->name . '/' . $file_name;
Log::info('Old File: ' . $old_file);
Log::info('New File: ' . $new_file);

//上传同名文件会导致md5自动命名,后期重命名回来
if (file_exists($old_file)) {
if (rename($old_file, $new_file)) {
Log::info('Rename Success');
$app_version['file_path'] = 'files/' . $app->name . '/' . $file_name;
$app_version->saveOrFail();
} else {
Log::info('Rename Failure');
}
}
}
});

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :