通过Laravel 4上传多张图片

时间:2015-04-13 04:00:04

标签: php laravel

如何通过laravel 4上传多张图片?使用下面的代码我只得到最后一张图片。如果我选择imgA,imgB,imgC和imgD,我只保存了imgD。我需要imgA,imgB,imgC和imgD。

public function store()
{
    $date = new DateTime();
    $timestamp = $date->format('U');
    $pid = Input::get('pid');

    $file = Input::file('image');

    if ($file->isValid()) {
        $destinationPath = public_path().'/images/';
        $oriname = Str::lower(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME));

        $extension = Input::file('image')->getClientOriginalExtension(); 
        $fileName = $timestamp.'_'.$oriname.'.'.$extension; 
        Input::file('image')->move($destinationPath, $fileName); 
        $url = asset('images/'.$fileName);
    }

    $newImage = New Image;
    $newImage->property_id = $pid;
    $newImage->path = $url;
    if ($newImage->save()){
        return array('status'=>'Image saved.'); 
    }

}

1 个答案:

答案 0 :(得分:0)

试试这样..

$date = new DateTime();
$timestamp = $date->format('U');
$pid = Input::get('pid');
$files = Input::file('image');

foreach ($files as $file) {
    if ($file->isValid()) {
        $destinationPath = public_path().'/images/';
        $oriname = Str::lower(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME));

        $extension = $file->getClientOriginalExtension(); 
        $fileName = $timestamp.'_'.$oriname.'.'.$extension; 
        $file->move($destinationPath, $fileName); 
        $url = asset('images/'.$fileName);
    }

    $newImage = New Image();
    $newImage->property_id = $pid;
    $newImage->path = $url;
    if (! $newImage->save()) {
        // error
    }
}

希望它对你有用。