Laravel - store()方法突然无法正常工作

时间:2017-09-19 23:21:13

标签: php laravel file symfony upload

我有一个文件上传方法,可以使用以下代码正确运行单个图像:

$file = $request->file('file');

if ($file && $file->isValid()) {
    $photo['size'] = $request->file('file')->getClientSize();
    $path = $request->file('file')->store($request->subdomain);
    $path = explode('/', $path);
    $photo['file'] = $path[1];
    $photo['cover'] = 1;
    $photo['gallery'] = $newGallery->id;
    $photo['uploaded_by'] = $user->id;
    Photo::create($photo);
}

$file此处是UploadedFile的实例,store()方法效果很好。

但是,我需要更改方法以允许上传多个文件。以下改编的代码可以识别以下错误:

$photos = $request->files->all();

    foreach($photos as $photo) {
        foreach($photo as $p) {

            if($p->isValid()) {
                $path = $p->store($request->subdomain);
                $path = explode('/', $path);

                $newPhoto = [
                    'uploaded_by' => $user->id,
                    'file' => $path[1],
                    'size' => $p->getClientSize(),
                    'gallery' => $request->gallery,
                    'subdomain' => $request->subdomain,
                ];

                Photo::create($requestData);
            }
        }
    }

Call to undefined method Symfony\Component\HttpFoundation\File\UploadedFile::store()

$p' dd输出:

UploadedFile {#28 ▼
  -test: false
  -originalName: "Untitled.png"
  -mimeType: "image/png"
  -size: 18030
  -error: 0
  path: "/tmp"
  filename: "phpBDSWCR"
  basename: "phpBDSWCR"
  pathname: "/tmp/phpBDSWCR"
  extension: ""
  realPath: "/tmp/phpBDSWCR"
  aTime: 2017-09-19 20:19:57
  mTime: 2017-09-19 20:19:57
  cTime: 2017-09-19 20:19:57
  inode: 3014878
  size: 18030
  perms: 0100600
  owner: 1000
  group: 1000
  type: "file"
  writable: true
  readable: true
  executable: false
  file: true
  dir: false
  link: false
}

这很奇怪,因为Laravel应该使用Illuminate\Http\UploadedFile具有正确的store()方法(docs)来对抗Symfony的类没有那个方法(docs

另外,使用Symfony move()会更糟糕,因为store()已经使用生成的文件名和扩展名保存了文件,因此我不必费心生成随机文件名并猜测扩展名,因为它不太可靠。

底线是:为什么它表现得那样,我怎样才能让它使用正确的类实例?

2 个答案:

答案 0 :(得分:3)

您只能使用您在请求实例上使用的商店方法。

也许你可以尝试做这样的事情

foreach($photo as $index => $p) {
    $request->file('files')[$index]->store();
}

答案 1 :(得分:0)

我也遇到同样的错误,上述解决方案有效: 这是更详细的一个:

$result = [];
//$photos = $request->file('files'); // just saving the line
foreach($request->file('files') as $k => $v) {
        $path = Storage::disk('public')->putFile('editor/uploads/1', $request->file('files')[$k]);
        $filename = basename($path);
        $result['url'] = $filename;
}

return $result;