Laravel |改变file()的realPath值

问题描述 投票:0回答:2

是否可以更改 Laravel 文件的

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

这是我转储 $request->file('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

php laravel file laravel-5 upload
2个回答
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.');
}

0
投票

您可以像这样移动文件

$file->move(public_path('uploads'), $file->originalName);
© www.soinside.com 2019 - 2024. All rights reserved.