本文规则:遵循post请求规则。$commodities为Model
必须:enctype="multipart/form-data"
本文涉及的依赖:
use Storage;
use Illuminate\Http\File;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
一:
一般文件上传思想:获取上传文件<strong>--></strong>判断是否有错<strong>--></strong>编写需要存储后文件名<strong>--></strong>移动文件到存储地址<strong>--></strong>写入数据库
$commodities = new Commodity;
$result = $commodities->fill($request->all());
$file = $request->file('picture');
// 文件是否上传成功
if($file->isValid()){
// 获取文件相关信息
$originalName = $file->getClientOriginalName(); // 文件原名
// 上传文件,没有使用PHP的默认单个POST请求发送的最大数据8M,而是改成了12M
$fileName = uniqid() . $originalName;
$movePath = $file->move(storage_path('app\uploads'),$fileName);
$saveDir = $movePath->getPath();
$savePath = $saveDir . $fileName;
// 使用put()集合函数将$filename作为文件名,file_get_contents()将文件的内容读入一个字符串
// $bool = Storage::disk('public')->put($filename, file_get_contents($realPath));
}
$result['picture'] = $savePath;
if ($result->save()) {
这种方式很粗鲁,但是不符合laravel的优雅
二:直接调用store(),会返回处理后的路径,具体实现请看UploadedFile.php,这个方法产生的文件名是随机生成的哦
$commodities = new Commodity;
//store()中的picture是文件夹名,不存在时自动创建在store\app
$path = $request->file('picture')->store('picture');
$result = $commodities->fill($request->all());
$result['picture'] = $path; //替换数组V
dd($result->save()); //返回true,就代表成功了
三:storeAs()路径、文件名、磁盘(可选的)作为它的参数
$commodities = new Commodity;
//store()中的picture是文件夹名,不存在时自动创建在store\app
$path = $request->file('picture')->storeAs('picture','asdf');
$result = $commodities->fill($request->all());
$result['picture'] = $path; //替换数组V
dd($result->save()); //返回true,就代表成功了
有错误请开启extension=php_fileinfo.dll扩展
另外,温馨提示:
上传文件的自定义名不要带原文件名,会出原文件名是中文的时候乱码bug!
希望本文对你有帮助;