Skip to content

Instantly share code, notes, and snippets.

@winwu
Last active January 13, 2017 04:44
Show Gist options
  • Save winwu/b5dd3076311962227fd2 to your computer and use it in GitHub Desktop.
Save winwu/b5dd3076311962227fd2 to your computer and use it in GitHub Desktop.
Laravel5-檔案上傳-多檔上傳.php
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Media;
use Validator;
use Request;
use Response;
//use Uuid;
class MediaController extends Controller
{
// 省略其他 method
public function store()
{
$files = Request::file('photo');
//print_r($files);
// 儲存成功的資料
$medias = [];
// 儲存失敗的資料
$errors = [];
foreach($files as $file) {
$rules = ['photo' => 'required|mimes:jpeg,bmp,png,jpg'];
$validator = Validator::make(['photo'=> $file], $rules);
if ($validator->fails()) {
array_push($errors, $validator->messages());
} else {
if ($file->isValid())
{
$media = new Media;
//設定要儲存的路徑
$destinationPath = base_path() . '/public/uploads';
// getting image extension
$extension = $file->getClientOriginalExtension();
// do other thing~... ex: resize, crop....
// 如果你有裝 uuid 的話 renameing image
// $fileName = Uuid::generate(4) . '_store_.' . $extension;
$fileName = $file->getClientOriginalName() . '.' . $extension;
// move file to dest
$file->move($destinationPath, $fileName);
// save data
$media->src = $fileName;
$media->save();
array_push($medias, $media);
}
}
}
//response success
return Response::json(
array(
'data' => $medias,
'error' => $errors
), 200);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment