Laravel |更改file()

时间:2018-05-09 13:43:09

标签: laravel file upload store laravel-5.6

是否可以更改Laravel文件的realPath属性?我实际上可以移动文件,但无法更改数据库记录,因为它记录为旧的realPath而不是新路径。

这是我转储$ request->文件后得到的结果(' xx');

UploadedFile {#476 ▼
  -test: false
  -originalName: "Screen Shot 2018-05-07 at 6.08.05 PM.png"
  -mimeType: "image/png"
  -size: 312932
  -error: 0
  #hashName: null
  path: "/Applications/MAMP/tmp/php"
  filename: "phpg4VH0Z"
  basename: "phpg4VH0Z"
  pathname: "/Applications/MAMP/tmp/php/phpg4VH0Z"
  extension: ""
  realPath: "/Applications/MAMP/tmp/php/phpg4VH0Z"
  aTime: 2018-05-09 13:33:43
  mTime: 2018-05-09 13:33:42
  cTime: 2018-05-09 13:33:42
  inode: 2003589
  size: 312932
  perms: 0100600
  owner: 501
  group: 80
  type: "file"
  writable: true
  readable: true
  executable: false
  file: true
  dir: false
  link: false
}

这是我的代码:

public function store(UploadRequest $request)
{
    $path = public_path('/uploads');

    $project = new Project($request->all());
    $project->save();

    foreach ($request->file() as $file) {
        dd($file);
        $fileName = time().'.'.$file->getClientOriginalExtension();
        $file->storeAs($path, $fileName);
    }

    return $request->all();
}

我想将文件保存在public / uploads文件夹中,并在数据库中使用自定义名称和相同的路径/名称。因为它现在保存为/Applications/MAMP/tmp/php/phpGQhReP

2 个答案:

答案 0 :(得分:0)

您可以像这样移动文件

$file->move(public_path('uploads'), $file->originalName);

答案 1 :(得分:0)

这应该可以解决问题,它假定您的<input文件名为file

public function store(UploadRequest $request)
{
    if ($request->hasFile('file')) { // depends on your FormRequest validation if `file` field is required or not
        $path = $request->file->storePublicly(public_path('/uploads'));
    }

    Project::create(array_merge($request->except('file'), ['file' => $path])); // do some array manipulation

    return $request->all();
}

这用于上传多个文件:

public function store(UploadRequest $request)
{
    foreach ($request->file() as $key => $file) {
        if ($request->hasFile($key)) {
            $path = $request->$key->storePublicly('/uploads');
        }
        $keys[]  = $key;
        $paths[] = $path;
    }
    $data = $request->except($keys);
    $data = array_merge($data, array_combine($keys, $paths));

    Project::create($data);

    return back()->with('success', 'Project has been created successfully.');
}