簡體   English   中英

Laravel 5:move() 函數不保存上傳的圖像文件

[英]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">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM