保存上传文件
Epona
4年前
修改理由:
此投稿已在 4年前 合并。
内容修改:
Old | New | Differences |
---|---|---|
1 | ||
1 | 假设我们上传头像文件。在 Laravel 中我们可以通过 `store`方法来进行存储: | |
2 | ||
3 | ```php | |
4 | <?php | |
5 | ||
6 | namespace App\Http\Controllers; | |
7 | ||
8 | use Illuminate\Http\Request; | |
9 | use App\Http\Controllers\Controller; | |
10 | ||
11 | class UserAvatarController extends Controller | |
12 | { | |
13 | /** | |
14 | * 更新用户头像. | |
15 | * | |
16 | * @param Request $request | |
17 | * @return Response | |
18 | */ | |
19 | public function update(Request $request) | |
20 | { | |
21 | $path = $request->file('avatar')->store('avatars'); | |
22 | ||
23 | return $path; | |
24 | } | |
25 | } | |
26 | ``` | |
27 | ||
28 | 上例有几个点需要注意。我们指定的是目录名,而不是文件名。默认情况下, `store` 方法会自动生成唯一的 ID 作为文件名。文件的扩展名将通过检查文件的 MIME 类型来确定。该文件的路径和文件名会被 `store` 方法返回,以便后续数据库的存储使用。 | |
29 | ||
30 | 你也可以使用 `Storage` facade 上的 `putFile` 方法达到和上例同样的效果: | |
31 | ||
32 | ```php | |
33 | $path = Storage::putFile('avatars', $request->file('avatar')); | |
34 | ``` | |
35 | ||
36 | ## 指定文件名 | |
37 | ||
38 | 如果你不想将文件名自动分配给存储的文件,可以使用 `storeAs` 方法,该方法接受路径,文件名和 (可选) 磁盘作为其参数: | |
39 | ||
40 | ```php | |
41 | $path = $request->file('avatar')->storeAs( | |
42 | 'avatars', $request->user()->id | |
43 | ); | |
44 | ``` | |
45 | ||
46 | 你可以使用 `Storage` facade 上的 `putFileAs` 方法达到和上例同样的文件操作: | |
47 | ||
48 | ```php | |
49 | $path = Storage::putFileAs( | |
50 | 'avatars', $request->file('avatar'), $request->user()->id | |
51 | ); | |
52 | ``` | |
53 | ||
54 | ## 指定磁盘 | |
55 | ||
56 | 默认情况下, `store` 方法使用默认磁盘。如果你需要指定其他的磁盘,可以传入磁盘名作为 `store` 方法的第二个参数: | |
57 | ||
58 | ```php | |
59 | $path = $request->file('avatar')->store( | |
60 | 'avatars/'.$request->user()->id, 's3' | |
61 | ); | |
62 | ``` |