Laravel 5:move()函数没有';t保存上传的图像文件


Laravel 5 : the move() function doesn't save the uploaded image file

我正在尝试用Laravel 5设置一个图像上传器。

这是表格。

    <form action="/edit/{{$id}}" method="POST" enctype="multipart/form-data">
        {!! csrf_field() !!}
        <input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
        <input type="hidden" name="_method" value="PUT">
            //There are other tags (including other input) here
            <input type="file" name="pic" accept="image/*">
        <input type="submit" value="Apply Changes">
    </form>

这是将从上面的form运行的控制器功能。

public function update($id)
{
    $this->model->find($id)->fill($this->request->all())->save();
    if ($this->request->hasFile('pic')) {
        $file = $this->request->file('pic');
        $name = $file->getClientOriginalName();
        $file->move('assets/serviceimages/', $name);
    }
    return redirect('/blahblah');
}

正如您可能已经注意到的,这并没有将上传的文件存储在assets/serviceimages/目录下,这正是我一直在尝试的。

基本上,我一直在学习本教程,但显然我遗漏了一些东西,而且完全不知道它是什么,即使在我看过API文档之后也是如此。

在控制器功能的if语句中,确认了$file$name符合我的预期。

因此,我怀疑问题出在move()函数上。

任何小建议都将不胜感激,因为这是我第一次尝试设置上传程序。

权限(如果您在Linux上)。如果这不起作用,试试这种方法:

$image = $request->file('pic');
$destinationPathImg = '/your path/images/';
if (!$image->move($destinationPathImg, $image->getClientOriginalName())) {
    return 'Error saving the file.';
}

此外,这需要添加到ur()中

public function update(Request $request, $id)

我发现必须使用存储适配器才能使用完整的文件路径

$storageAdapter = Storage::disk('v1')->getDriver()->getAdapter()
$full_path_before = $storageAdapter->applyPathPrefix($oldPath);
$full_path_after = $storageAdapter->applyPathPrefix($newPath);
if (!File::exists($full_path_before)){
   throw new 'Exception("Error moving folders");
}
$move_files = $full_path_after !== $full_path_before;
if ($move_files){
   File::move($full_path_before, $full_path_after);
}

使用此方法将100%工作

if($request->hasFile('filename')){
     $file = $request->filename;
    $file_new_name =  $file->move("upload/posts/", $file->getClientOriginalName());
    $post->filename = $file_new_names;
   }

记住文件名是您的<img name="filename">