上一篇
创建包含文件上传字段的表单:
<form action="/upload" method="POST" enctype="multipart/form-data"> <input type="file" name="file"> <button type="submit">上传</button> </form>
在控制器中使用Request
对象处理文件上传:
use Illuminate\Http\Request; public function upload(Request $request) { if ($request->hasFile('file')) { $file = $request->file('file'); $filename = $file->getClientOriginalName(); $file->move(public_path('uploads'), $filename); return back()->with('success', '文件上传成功!'); } }
store()
保存到指定路径:$path = $request->file('file')->store('uploads');
$path = $request->file('avatar')->storeAs('avatars', 'custom_name.jpg');
在控制器中返回下载响应:
public function download($filename) { $file = public_path('uploads/' . $filename); return response()->download($file, '自定义文件名.jpg'); }
定义下载路由:
Route::get('/download/{filename}', 'DownloadController@download');
return response()->download($file)->setHeader('Content-Type', 'application/pdf');
return response()->stream(function () use ($file) { readfile($file); }, 200, ['Content-Type' => 'application/octet-stream']);
修改config/filesystems.php
,配置本地或云存储(如腾讯云COS):
'disks' => [ 'public' => [ 'driver' => 'local', 'root' => storage_path('app/public'), 'url' => env('APP_URL').'/storage', ], ],
use Illuminate\Support\Facades\Storage; // 保存文件 Storage::disk('public')->put('demo.txt', '内容'); // 获取文件内容 $content = Storage::disk('public')->get('demo.txt'); // 删除文件 Storage::disk('public')->delete('demo.txt');
use Illuminate\Support\Facades\Http; $response = Http::get('https://example.com/file.zip'); $file = file_put_contents('local_file.zip', $response->body());
$request->validate([ 'file' => 'required|file|mimes:jpg,png|max:2048', ]);
basename()
过滤文件名。生成表单请求类:
php artisan make:request FileUploadRequest
在请求类中定义验证规则:
public function rules() { return [ 'file' => 'required|file|max:10240', ]; }
生成单一动作控制器:
php artisan make:controller FileDownloadController --invokable
use App\Jobs\ProcessFileUpload; ProcessFileUpload::dispatch($file)->onQueue('uploads');
Laravel提供了强大的文件操作工具,结合Storage门面、路由和控制器,可轻松实现文件上传、下载和管理,通过合理配置存储系统、验证文件安全性,并利用队列优化性能,能构建高效可靠的文件处理功能,记得定期更新框架和包,保持代码安全与兼容性! 💡
本文由 业务大全 于2025-08-25发表在【云服务器提供商】,文中图片由(业务大全)上传,本平台仅提供信息存储服务;作者观点、意见不代表本站立场,如有侵权,请联系我们删除;若有图片侵权,请您准备原始证明材料和公证书后联系我方删除!
本文链接:https://vps.7tqx.com/wenda/730175.html
发表评论