laravel 上傳 php 需要開啟 fileinfo 擴展
先看一個例子:
$file = $request->file('shopimg'); $path = $file->store('public/avatars'); echo $path; //給storage目錄public/avatars/ 上傳文件 //獲取文件內容 $contents = Storage::get('public\avatars\file.jpg'); //echo $contents; //判斷文件是否存在 1 $exists = Storage::disk('local')->exists('public/avatars/file.jpg'); //echo $exists;
正文:
aravel文件系統
Laravel框架中對文件的管理已經很友好了,官方文檔也做了很詳細的說明,下面先就一些基礎知識做下簡單介紹,已了解的同學可以略過本部分。
系統配置
Laravel 有強大的文件系統抽象,基於Frank de Jonge 開發的PHP包,文件系統的配置文件位於 config/filesystems.php
公共磁盤
public 磁盤用於存儲可以被公開訪問的文件,默認情況下, public 磁盤使用 local 驅動並將文件存儲在 storage/app/public ,要讓這些文件可以通過web訪問到,需要創建一個軟鏈 public/storage 指向 storage/app/public ,這種方式可以將公開訪問的文件保存在一個可以很容易被不同部署環境共享的目錄,在使用零停機時間部署系統如Envoyer的時候尤其方便。
獲取文件
get 方法用於獲取指定文件
__exists__方法用於判斷給定文件是否存在於磁盤上:
$contents = Storage::get('file.jpg'); $exists = Storage::disk('s3')->exists('file.jpg');
文件上傳
在web應用中,最常見的存儲文件案例就是存儲用戶上傳的文件,如用戶頭像、照片和文檔等。Laravel通過使用上傳文件實例上的store方法讓存儲上傳文件變得簡單。你只需要傳入上傳文件保存的路徑並調用store方法即可:
$path = $request->file('avatar')->store('avatars');
指定文件名
$path = $request->file('avatar')->storeAs( 'avatars', $request->user()->id );
文件刪除
Storage::delete(['file1.jpg', 'file2.jpg']);
自定義文件上傳
使用Laravel文件上傳很方便,在開發中我們需要創建軟連接,但是有可能具體項目中不需要創建軟連接,或者需要直接在公共盤 public 下面就能直接訪問文件,這個時候就需要調整一下配置文件。
默認的驅動是__local__ 驅動 (config/filesystems.php):
'disks' => [ 'local' => [ 'driver' => 'local', 'root' => storage_path('app'), ], 'public' => [ 'driver' => 'local', 'root' => storage_path('app/public'), 'visibility' => 'public', ], 's3' => [ 'driver' => 's3', 'key' => 'your-key', 'secret' => 'your-secret', 'region' => 'your-region', 'bucket' => 'your-bucket', ], ],
我們增加一條驅動信息:
'root' => [ 'driver' => 'local', 'root' => base_path(''), ], 'local' => [ 'driver' => 'local', 'root' => public_path(''), ],
這樣該驅動指向項目根目錄,然后我們在上傳處理函數中:
$path = $request->file('avatar')->store( 'public/avatars/test.png', 'root' );
判斷文件是否存在或者刪除文件時:
Storage::disk('root')->delete($imagePath);
base_path 就是項目根目錄
app_path 就是項目下App文件夾
storage_path 就是項目下的storage文件夾
1、獲取上傳的文件
$file=$request->file('file');
2、獲取上傳文件的文件名(帶后綴,如abc.png)
$filename=$file->getClientOriginalName();
3、獲取上傳文件的后綴(如abc.png,獲取到的為png)
$fileextension=$file->getClientOriginalExtension();
4、獲取上傳文件的大小
$filesize=$file->getClientSize();
5、獲取緩存在tmp目錄下的文件名(帶后綴,如php8933.tmp)
$filaname=$file->getFilename();
6、獲取上傳的文件緩存在tmp文件夾下的絕對路徑
$realpath=$file->getRealPath();
7、將緩存在tmp目錄下的文件移到某個位置,返回的是這個文件移動過后的路徑
$path=$file->move(path,newname);
move()方法有兩個參數,第一個參數是文件移到哪個文件夾下的路徑,第二個參數是將上傳的文件重新命名的文件名
8、檢測上傳的文件是否合法,返回值為true或false
$file->isValid()
轉 https://blog.csdn.net/guawawa311/article/details/83057983
https://laravelacademy.org/post/19509.html
https://www.cnblogs.com/blog-dyn/p/10310393.html