基于Laravel开发博客应用系列 —— 实现文件上传管理功能

1、配置本地文件系统

让我们从配置开始吧,我们在 public 目录下创建一个 uploads 目录用来存放上传的文件,这样所有上传文件都可以通过浏览器直接访问。

首先我们在博客项目目录下使用如下命令在 public 目录下创建 uploads 子目录:

为Laravel博客创建文件保存目录

很简单。接下来我们来编辑 config/blog.php

  1. <?php
  2. return [
  3. 'title' => 'My Blog',
  4. 'posts_per_page' => 5,
  5. 'uploads' => [
  6. 'storage' => 'local',
  7. 'webpath' => '/uploads',
  8. ],
  9. ];

我们在 uploads 配置项中使用 storage 定义使用的文件系统,使用 webpath 定义 web 访问根目录。

最后,编辑config/filesystems.php 如下:

  1. //将如下区块代码
  2. 'disks' => [
  3. 'local' => [
  4. 'driver' => 'local',
  5. 'root' => storage_path('app'),
  6. ],
  7. // 修改成这样
  8. 'disks' => [
  9. 'local' => [
  10. 'driver' => 'local',
  11. 'root' => public_path('uploads'),
  12. ],

我们将本地存储的根目录修改为前面创建的 public/uploads 目录。

2、创建帮助函数文件

在 Laravel 5.1 项目中有时我们会需要一些不依赖于类的辅助函数,通常我们会将这些辅助函数定义在一个单独文件如 helpers.php 中。我们在 app 目录下创建这个名为 helpers.php 的文件,并编辑其内容如下:

  1. <?php
  2. /**
  3. * 返回可读性更好的文件尺寸
  4. */
  5. function human_filesize($bytes, $decimals = 2)
  6. {
  7. $size = ['B', 'kB', 'MB', 'GB', 'TB', 'PB'];
  8. $factor = floor((strlen($bytes) - 1) / 3);
  9. return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) .@$size[$factor];
  10. }
  11. /**
  12. * 判断文件的MIME类型是否为图片
  13. */
  14. function is_image($mimeType)
  15. {
  16. return starts_with($mimeType, 'image/');
  17. }

其中 human_filesize() 函数返回一个易读的文件尺寸,is_image() 函数在文件类型为图片的时候返回 true。

要让应用能够正确找到 helpers.php 文件,还要修改项目根目录下的 composer.json

  1. {
  2. ...
  3. "autoload": {
  4. "classmap": [
  5. "database"
  6. ],
  7. "psr-4": {
  8. "App\\": "app/"
  9. },
  10. "files": [
  11. "app/helpers.php"
  12. ]
  13. },
  14. ...
  15. }

在 autoload 配置项的 files 数组中指定要被加载的文件/文件夹。修改完成后记得运行 composer dumpauto 确保修改生效:

  1. composer dumpauto

现在 helpers.php 中的所有函数都会载入到自动加载器中,你可以在博客应用的代码中任意使用其中的函数。

3、创建文件上传管理服务

现在基本配置已经完成了,让我们创建一个服务类来管理上传文件。

检测文件 MIME 类型

我们想要基于不同类型的上传文件进行不同的操作,这可以通过检测上传文件 MIME 类型轻松实现。

PHP 有一个内置函数 mime_content_type() 用于检测文件的MIME类型,但是该函数已经废弃了,我们使用另一个解决方案。

在 Packagist 中搜索 “mime” 会查询到一个名为 dflydev 的包,我们在博客项目中使用 Composer 安装该依赖包:

  1. composer require "dflydev/apache-mime-types"

我们将使用该依赖包提供的方法来检测文件的 MIME 类型。

创建UploadsManager

app/Services 目录下创建 UploadsManager.php,编辑其内容如下:

  1. <?php
  2. namespace App\Services;
  3. use Carbon\Carbon;
  4. use Dflydev\ApacheMimeTypes\PhpRepository;
  5. use Illuminate\Support\Facades\Storage;
  6. class UploadsManager
  7. {
  8. protected $disk;
  9. protected $mimeDetect;
  10. public function __construct(PhpRepository $mimeDetect)
  11. {
  12. $this->disk = Storage::disk(config('blog.uploads.storage'));
  13. $this->mimeDetect = $mimeDetect;
  14. }
  15. /**
  16. * Return files and directories within a folder
  17. *
  18. * @param string $folder
  19. * @return array of [
  20. * 'folder' => 'path to current folder',
  21. * 'folderName' => 'name of just current folder',
  22. * 'breadCrumbs' => breadcrumb array of [ $path => $foldername ]
  23. * 'folders' => array of [ $path => $foldername] of each subfolder
  24. * 'files' => array of file details on each file in folder
  25. * ]
  26. */
  27. public function folderInfo($folder)
  28. {
  29. $folder = $this->cleanFolder($folder);
  30. $breadcrumbs = $this->breadcrumbs($folder);
  31. $slice = array_slice($breadcrumbs, -1);
  32. $folderName = current($slice);
  33. $breadcrumbs = array_slice($breadcrumbs, 0, -1);
  34. $subfolders = [];
  35. foreach (array_unique($this->disk->directories($folder)) as $subfolder) {
  36. $subfolders["/$subfolder"] = basename($subfolder);
  37. }
  38. $files = [];
  39. foreach ($this->disk->files($folder) as $path) {
  40. $files[] = $this->fileDetails($path);
  41. }
  42. return compact(
  43. 'folder',
  44. 'folderName',
  45. 'breadcrumbs',
  46. 'subfolders',
  47. 'files'
  48. );
  49. }
  50. /**
  51. * Sanitize the folder name
  52. */
  53. protected function cleanFolder($folder)
  54. {
  55. return '/' . trim(str_replace('..', '', $folder), '/');
  56. }
  57. /**
  58. * 返回当前目录路径
  59. */
  60. protected function breadcrumbs($folder)
  61. {
  62. $folder = trim($folder, '/');
  63. $crumbs = ['/' => 'root'];
  64. if (empty($folder)) {
  65. return $crumbs;
  66. }
  67. $folders = explode('/', $folder);
  68. $build = '';
  69. foreach ($folders as $folder) {
  70. $build .= '/'.$folder;
  71. $crumbs[$build] = $folder;
  72. }
  73. return $crumbs;
  74. }
  75. /**
  76. * 返回文件详细信息数组
  77. */
  78. protected function fileDetails($path)
  79. {
  80. $path = '/' . ltrim($path, '/');
  81. return [
  82. 'name' => basename($path),
  83. 'fullPath' => $path,
  84. 'webPath' => $this->fileWebpath($path),
  85. 'mimeType' => $this->fileMimeType($path),
  86. 'size' => $this->fileSize($path),
  87. 'modified' => $this->fileModified($path),
  88. ];
  89. }
  90. /**
  91. * 返回文件完整的web路径
  92. */
  93. public function fileWebpath($path)
  94. {
  95. $path = rtrim(config('blog.uploads.webpath'), '/') . '/' .ltrim($path, '/');
  96. return url($path);
  97. }
  98. /**
  99. * 返回文件MIME类型
  100. */
  101. public function fileMimeType($path)
  102. {
  103. return $this->mimeDetect->findType(
  104. pathinfo($path, PATHINFO_EXTENSION)
  105. );
  106. }
  107. /**
  108. * 返回文件大小
  109. */
  110. public function fileSize($path)
  111. {
  112. return $this->disk->size($path);
  113. }
  114. /**
  115. * 返回最后修改时间
  116. */
  117. public function fileModified($path)
  118. {
  119. return Carbon::createFromTimestamp(
  120. $this->disk->lastModified($path)
  121. );
  122. }
  123. }

4、实现文件上传管理列表

现在 UploadsManager 服务类已经创建,接下来我们来实现控制器的 index 方法。

创建 index 方法

编辑 app/Http/Controllers/Admin 目录下的 UploadController.php 文件内容如下:

  1. <?php
  2. namespace App\Http\Controllers\Admin;
  3. use App\Http\Controllers\Controller;
  4. use App\Services\UploadsManager;
  5. use Illuminate\Http\Request;
  6. class UploadController extends Controller
  7. {
  8. protected $manager;
  9. public function __construct(UploadsManager $manager)
  10. {
  11. $this->manager = $manager;
  12. }
  13. /**
  14. * Show page of files / subfolders
  15. */
  16. public function index(Request $request)
  17. {
  18. $folder = $request->get('folder');
  19. $data = $this->manager->folderInfo($folder);
  20. return view('admin.upload.index', $data);
  21. }
  22. }

构造方法中注入了 UploadsManager 依赖,在 index() 方法中只需传入 folderInfo() 返回的数据到要渲染的视图并返回即可。

你可能已经注意到 $folder 从请求中获取,是的,我们只需要通过请求参数即可实现文件夹修改。

创建 index 视图

resources/views/admin 目录下新建 upload 目录,并在该目录下创建 index.blade.php 文件,编辑该文件内容如下:

  1. @extends('admin.layout')
  2. @section('content')
  3. <div class="container-fluid">
  4. {{-- 顶部工具栏 --}}
  5. <div class="row page-title-row">
  6. <div class="col-md-6">
  7. <h3 class="pull-left">Uploads </h3>
  8. <div class="pull-left">
  9. <ul class="breadcrumb">
  10. @foreach ($breadcrumbs as $path => $disp)
  11. <li><a href="/admin/upload?folder={{ $path }}">{{ $disp }}</a></li>
  12. @endforeach
  13. <li class="active">{{ $folderName }}</li>
  14. </ul>
  15. </div>
  16. </div>
  17. <div class="col-md-6 text-right">
  18. <button type="button" class="btn btn-success btn-md" data-toggle="modal" data-target="#modal-folder-create">
  19. <i class="fa fa-plus-circle"></i> New Folder
  20. </button>
  21. <button type="button" class="btn btn-primary btn-md" data-toggle="modal" data-target="#modal-file-upload">
  22. <i class="fa fa-upload"></i> Upload
  23. </button>
  24. </div>
  25. </div>
  26. <div class="row">
  27. <div class="col-sm-12">
  28. @include('admin.partials.errors')
  29. @include('admin.partials.success')
  30. <table id="uploads-table" class="table table-striped table-bordered">
  31. <thead>
  32. <tr>
  33. <th>Name</th>
  34. <th>Type</th>
  35. <th>Date</th>
  36. <th>Size</th>
  37. <th data-sortable="false">Actions</th>
  38. </tr>
  39. </thead>
  40. <tbody>
  41. {{-- 子目录 --}}
  42. @foreach ($subfolders as $path => $name)
  43. <tr>
  44. <td>
  45. <a href="/admin/upload?folder={{ $path }}">
  46. <i class="fa fa-folder fa-lg fa-fw"></i>
  47. {{ $name }}
  48. </a>
  49. </td>
  50. <td>Folder</td>
  51. <td>-</td>
  52. <td>-</td>
  53. <td>
  54. <button type="button" class="btn btn-xs btn-danger" onclick="delete_folder('{{ $name }}')">
  55. <i class="fa fa-times-circle fa-lg"></i>
  56. Delete
  57. </button>
  58. </td>
  59. </tr>
  60. @endforeach
  61. {{-- 所有文件 --}}
  62. @foreach ($files as $file)
  63. <tr>
  64. <td>
  65. <a href="{{ $file['webPath'] }}">
  66. @if (is_image($file['mimeType']))
  67. <i class="fa fa-file-image-o fa-lg fa-fw"></i>
  68. @else
  69. <i class="fa fa-file-o fa-lg fa-fw"></i>
  70. @endif
  71. {{ $file['name'] }}
  72. </a>
  73. </td>
  74. <td>{{ $file['mimeType'] or 'Unknown' }}</td>
  75. <td>{{ $file['modified']->format('j-M-y g:ia') }}</td>
  76. <td>{{ human_filesize($file['size']) }}</td>
  77. <td>
  78. <button type="button" class="btn btn-xs btn-danger" onclick="delete_file('{{ $file['name'] }}')">
  79. <i class="fa fa-times-circle fa-lg"></i>
  80. Delete
  81. </button>
  82. @if (is_image($file['mimeType']))
  83. <button type="button" class="btn btn-xs btn-success" onclick="preview_image('{{ $file['webPath'] }}')">
  84. <i class="fa fa-eye fa-lg"></i>
  85. Preview
  86. </button>
  87. @endif
  88. </td>
  89. </tr>
  90. @endforeach
  91. </tbody>
  92. </table>
  93. </div>
  94. </div>
  95. </div>
  96. @include('admin.upload._modals')
  97. @stop
  98. @section('scripts')
  99. <script>
  100. // 确认文件删除
  101. function delete_file(name) {
  102. $("#delete-file-name1").html(name);
  103. $("#delete-file-name2").val(name);
  104. $("#modal-file-delete").modal("show");
  105. }
  106. // 确认目录删除
  107. function delete_folder(name) {
  108. $("#delete-folder-name1").html(name);
  109. $("#delete-folder-name2").val(name);
  110. $("#modal-folder-delete").modal("show");
  111. }
  112. // 预览图片
  113. function preview_image(path) {
  114. $("#preview-image").attr("src", path);
  115. $("#modal-image-view").modal("show");
  116. }
  117. // 初始化数据
  118. $(function() {
  119. $("#uploads-table").DataTable();
  120. });
  121. </script>
  122. @stop

尽管这个模板文件很长,但是理解起来并没有什么困难,所有文件上传和下载管理都将在这里进行。

有没有注意到我们在最后包含了 admin.upload._modals?是的,我们将模态对话框放到了一个单独的视图模板中。现在,我们在 resources/views/admin/upload 目录下创建一个空的_modals.blade.php 文件。

上传管理界面

打开浏览器,进入博客应用后台管理页面,点击顶部导航条的“上传”(Uploads)链接,将会跳转到如下页面:

Laravel博客后台文件上传列表

既漂亮又清爽,有木有?接下来让我们来实现所有的模态对话框及其背后的业务逻辑。

5、完成文件上传管理功能

对于完整的文件上传管理器而言剩下的工作已经不多了,现在是时候完成所有功能了。

添加路由

我们需要为上传管理器定义所有需要的路由,编辑 app/Http/routes.php 添加如下路由:

  1. // 在这一行下面
  2. get('admin/upload', 'UploadController@index');
  3. // 添加如下路由
  4. post('admin/upload/file', 'UploadController@uploadFile');
  5. delete('admin/upload/file', 'UploadController@deleteFile');
  6. post('admin/upload/folder', 'UploadController@createFolder');
  7. delete('admin/upload/folder', 'UploadController@deleteFolder');

定义所有模态对话框

编辑我们之前创建的 _modals.blade.php 文件内容如下:

  1. {{-- 创建目录 --}}
  2. <div class="modal fade" id="modal-folder-create">
  3. <div class="modal-dialog">
  4. <div class="modal-content">
  5. <form method="POST" action="/admin/upload/folder" class="form-horizontal">
  6. <input type="hidden" name="_token" value="{{ csrf_token() }}">
  7. <input type="hidden" name="folder" value="{{ $folder }}">
  8. <div class="modal-header">
  9. <button type="button" class="close" data-dismiss="modal">
  10. ×
  11. </button>
  12. <h4 class="modal-title">Create New Folder</h4>
  13. </div>
  14. <div class="modal-body">
  15. <div class="form-group">
  16. <label for="new_folder_name" class="col-sm-3 control-label">
  17. Folder Name
  18. </label>
  19. <div class="col-sm-8">
  20. <input type="text" id="new_folder_name" name="new_folder" class="form-control">
  21. </div>
  22. </div>
  23. </div>
  24. <div class="modal-footer">
  25. <button type="button" class="btn btn-default" data-dismiss="modal">
  26. Cancel
  27. </button>
  28. <button type="submit" class="btn btn-primary">
  29. Create Folder
  30. </button>
  31. </div>
  32. </form>
  33. </div>
  34. </div>
  35. </div>
  36. {{-- 删除文件 --}}
  37. <div class="modal fade" id="modal-file-delete">
  38. <div class="modal-dialog">
  39. <div class="modal-content">
  40. <div class="modal-header">
  41. <button type="button" class="close" data-dismiss="modal">
  42. ×
  43. </button>
  44. <h4 class="modal-title">Please Confirm</h4>
  45. </div>
  46. <div class="modal-body">
  47. <p class="lead">
  48. <i class="fa fa-question-circle fa-lg"></i>
  49. Are you sure you want to delete the
  50. <kbd><span id="delete-file-name1">file</span></kbd>
  51. file?
  52. </p>
  53. </div>
  54. <div class="modal-footer">
  55. <form method="POST" action="/admin/upload/file">
  56. <input type="hidden" name="_token" value="{{ csrf_token() }}">
  57. <input type="hidden" name="_method" value="DELETE">
  58. <input type="hidden" name="folder" value="{{ $folder }}">
  59. <input type="hidden" name="del_file" id="delete-file-name2">
  60. <button type="button" class="btn btn-default" data-dismiss="modal">
  61. Cancel
  62. </button>
  63. <button type="submit" class="btn btn-danger">
  64. Delete File
  65. </button>
  66. </form>
  67. </div>
  68. </div>
  69. </div>
  70. </div>
  71. {{-- 删除目录 --}}
  72. <div class="modal fade" id="modal-folder-delete">
  73. <div class="modal-dialog">
  74. <div class="modal-content">
  75. <div class="modal-header">
  76. <button type="button" class="close" data-dismiss="modal">
  77. ×
  78. </button>
  79. <h4 class="modal-title">Please Confirm</h4>
  80. </div>
  81. <div class="modal-body">
  82. <p class="lead">
  83. <i class="fa fa-question-circle fa-lg"></i>
  84. Are you sure you want to delete the
  85. <kbd><span id="delete-folder-name1">folder</span></kbd>
  86. folder?
  87. </p>
  88. </div>
  89. <div class="modal-footer">
  90. <form method="POST" action="/admin/upload/folder">
  91. <input type="hidden" name="_token" value="{{ csrf_token() }}">
  92. <input type="hidden" name="_method" value="DELETE">
  93. <input type="hidden" name="folder" value="{{ $folder }}">
  94. <input type="hidden" name="del_folder" id="delete-folder-name2">
  95. <button type="button" class="btn btn-default" data-dismiss="modal">
  96. Cancel
  97. </button>
  98. <button type="submit" class="btn btn-danger">
  99. Delete Folder
  100. </button>
  101. </form>
  102. </div>
  103. </div>
  104. </div>
  105. </div>
  106. {{-- 上传文件 --}}
  107. <div class="modal fade" id="modal-file-upload">
  108. <div class="modal-dialog">
  109. <div class="modal-content">
  110. <form method="POST" action="/admin/upload/file" class="form-horizontal" enctype="multipart/form-data">
  111. <input type="hidden" name="_token" value="{{ csrf_token() }}">
  112. <input type="hidden" name="folder" value="{{ $folder }}">
  113. <div class="modal-header">
  114. <button type="button" class="close" data-dismiss="modal">
  115. ×
  116. </button>
  117. <h4 class="modal-title">Upload New File</h4>
  118. </div>
  119. <div class="modal-body">
  120. <div class="form-group">
  121. <label for="file" class="col-sm-3 control-label">
  122. File
  123. </label>
  124. <div class="col-sm-8">
  125. <input type="file" id="file" name="file">
  126. </div>
  127. </div>
  128. <div class="form-group">
  129. <label for="file_name" class="col-sm-3 control-label">
  130. Optional Filename
  131. </label>
  132. <div class="col-sm-4">
  133. <input type="text" id="file_name" name="file_name" class="form-control">
  134. </div>
  135. </div>
  136. </div>
  137. <div class="modal-footer">
  138. <button type="button" class="btn btn-default" data-dismiss="modal">
  139. Cancel
  140. </button>
  141. <button type="submit" class="btn btn-primary">
  142. Upload File
  143. </button>
  144. </div>
  145. </form>
  146. </div>
  147. </div>
  148. </div>
  149. {{-- 浏览图片 --}}
  150. <div class="modal fade" id="modal-image-view">
  151. <div class="modal-dialog">
  152. <div class="modal-content">
  153. <div class="modal-header">
  154. <button type="button" class="close" data-dismiss="modal">
  155. ×
  156. </button>
  157. <h4 class="modal-title">Image Preview</h4>
  158. </div>
  159. <div class="modal-body">
  160. <img id="preview-image" src="x" class="img-responsive">
  161. </div>
  162. <div class="modal-footer">
  163. <button type="button" class="btn btn-default" data-dismiss="modal">
  164. Cancel
  165. </button>
  166. </div>
  167. </div>
  168. </div>
  169. </div>

在该文件中总共有5个不同的模态弹出框,分别对应上面定义的5个路由。

添加表单请求验证类

使用 Artisan 命令创建 UploadFileRequest,并编辑其内容如下:

  1. <?php
  2. namespace App\Http\Requests;
  3. use App\Http\Requests\Request;
  4. class UploadFileRequest extends Request
  5. {
  6. /**
  7. * Determine if the user is authorized to make this request.
  8. *
  9. * @return bool
  10. */
  11. public function authorize()
  12. {
  13. return true;
  14. }
  15. /**
  16. * Get the validation rules that apply to the request.
  17. *
  18. * @return array
  19. */
  20. public function rules()
  21. {
  22. return [
  23. 'file' => 'required',
  24. 'folder' => 'required',
  25. ];
  26. }
  27. }

使用 Artisan 命令创建 UploadNewFolderRequest,并编辑其内容如下:

  1. <?php
  2. namespace App\Http\Requests;
  3. use App\Http\Requests\Request;
  4. class UploadNewFolderRequest extends Request
  5. {
  6. /**
  7. * Determine if the user is authorized to make this request.
  8. *
  9. * @return bool
  10. */
  11. public function authorize()
  12. {
  13. return true;
  14. }
  15. /**
  16. * Get the validation rules that apply to the request.
  17. *
  18. * @return array
  19. */
  20. public function rules()
  21. {
  22. return [
  23. 'folder' => 'required',
  24. 'new_folder' => 'required',
  25. ];
  26. }
  27. }

同样,这些请求类用于验证表单输入。

完成 UploadController 所有方法
编辑 UploadController.php 文件内容如下:

  1. <?php
  2. // 添加如下三个use语句到UploadController控制器顶部
  3. use App\Http\Requests\UploadFileRequest;
  4. use App\Http\Requests\UploadNewFolderRequest;
  5. use Illuminate\Support\Facades\File;
  6. // 添加如下四个方法到UploadController控制器类
  7. /**
  8. * 创建新目录
  9. */
  10. public function createFolder(UploadNewFolderRequest $request)
  11. {
  12. $new_folder = $request->get('new_folder');
  13. $folder = $request->get('folder').'/'.$new_folder;
  14. $result = $this->manager->createDirectory($folder);
  15. if ($result === true) {
  16. return redirect()
  17. ->back()
  18. ->withSuccess("Folder '$new_folder' created.");
  19. }
  20. $error = $result ? : "An error occurred creating directory.";
  21. return redirect()
  22. ->back()
  23. ->withErrors([$error]);
  24. }
  25. /**
  26. * 删除文件
  27. */
  28. public function deleteFile(Request $request)
  29. {
  30. $del_file = $request->get('del_file');
  31. $path = $request->get('folder').'/'.$del_file;
  32. $result = $this->manager->deleteFile($path);
  33. if ($result === true) {
  34. return redirect()
  35. ->back()
  36. ->withSuccess("File '$del_file' deleted.");
  37. }
  38. $error = $result ? : "An error occurred deleting file.";
  39. return redirect()
  40. ->back()
  41. ->withErrors([$error]);
  42. }
  43. /**
  44. * 删除目录
  45. */
  46. public function deleteFolder(Request $request)
  47. {
  48. $del_folder = $request->get('del_folder');
  49. $folder = $request->get('folder').'/'.$del_folder;
  50. $result = $this->manager->deleteDirectory($folder);
  51. if ($result === true) {
  52. return redirect()
  53. ->back()
  54. ->withSuccess("Folder '$del_folder' deleted.");
  55. }
  56. $error = $result ? : "An error occurred deleting directory.";
  57. return redirect()
  58. ->back()
  59. ->withErrors([$error]);
  60. }
  61. /**
  62. * 上传文件
  63. */
  64. public function uploadFile(UploadFileRequest $request)
  65. {
  66. $file = $_FILES['file'];
  67. $fileName = $request->get('file_name');
  68. $fileName = $fileName ?: $file['name'];
  69. $path = str_finish($request->get('folder'), '/') . $fileName;
  70. $content = File::get($file['tmp_name']);
  71. $result = $this->manager->saveFile($path, $content);
  72. if ($result === true) {
  73. return redirect()
  74. ->back()
  75. ->withSuccess("File '$fileName' uploaded.");
  76. }
  77. $error = $result ? : "An error occurred uploading file.";
  78. return redirect()
  79. ->back()
  80. ->withErrors([$error]);
  81. }
  82. 完成 UploadsManager 服务类
  83. 最后编辑 app/Services/UploadsManager.php 内容如下:
  84. <?php
  85. // 在该类中新增以下4个方法
  86. /**
  87. * 创建新目录
  88. */
  89. public function createDirectory($folder)
  90. {
  91. $folder = $this->cleanFolder($folder);
  92. if ($this->disk->exists($folder)) {
  93. return "Folder '$folder' already exists.";
  94. }
  95. return $this->disk->makeDirectory($folder);
  96. }
  97. /**
  98. * 删除目录
  99. */
  100. public function deleteDirectory($folder)
  101. {
  102. $folder = $this->cleanFolder($folder);
  103. $filesFolders = array_merge(
  104. $this->disk->directories($folder),
  105. $this->disk->files($folder)
  106. );
  107. if (! empty($filesFolders)) {
  108. return "Directory must be empty to delete it.";
  109. }
  110. return $this->disk->deleteDirectory($folder);
  111. }
  112. /**
  113. * 删除文件
  114. */
  115. public function deleteFile($path)
  116. {
  117. $path = $this->cleanFolder($path);
  118. if (! $this->disk->exists($path)) {
  119. return "File does not exist.";
  120. }
  121. return $this->disk->delete($path);
  122. }
  123. /**
  124. * 保存文件
  125. */
  126. public function saveFile($path, $content)
  127. {
  128. $path = $this->cleanFolder($path);
  129. if ($this->disk->exists($path)) {
  130. return "File already exists.";
  131. }
  132. return $this->disk->put($path, $content);
  133. }

至此,已经完成了文件上传管理的所有工作,可以去浏览器完成上传文件、创建目录、删除文件等操作了。

6、测试文件上传和删除功能

在浏览器中访问管理面板创建新目录,在弹出的模态对话框中填写表单:

点击“Create Folder”提交表单,创建目录成功:

点击进入新创建的子目录 laravelacademy,在该目录下点击“Upload”按钮上传文件:

点击“Upload File”上传文件,上传成功后跳转到文件列表:

但是去 public/uploads/laravelacademy 目录下查看,上传的文件 Laravel学院 并没有扩展名,而且上面列表里 Type 类型值为 Unkown,预览按钮没显示出来也说明了有问题,正确的文件名应该包含扩展名,看来是上传图片时填写的文件名称有问题,应该这样填写为 LaravelAcademy.jpg,这样重新上传后文件列表显示如下:

这样数据都对了,预览按钮也显示出来了,点击“Preview”按钮,页面显示如下:

最后我们将无效的Laravel学院文件删除,点击其对应的“Delete”按钮,页面弹出确认删除对话框:

点击“Delete File”,确认删除。



评论 0

发表评论

Top