Skip to content

Instantly share code, notes, and snippets.

@winwu
Created August 1, 2015 03:14
Show Gist options
  • Save winwu/1125fbf0d3cfa373ebac to your computer and use it in GitHub Desktop.
Save winwu/1125fbf0d3cfa373ebac to your computer and use it in GitHub Desktop.
Laravel5-檔案上傳-單檔上傳.php
<?php
use App\Http\Controllers\Controller;
use App\Media;
use Validator;
use Request;
use Response;
use Uuid;
class MediaController extends Controller
{
// 省略其他 method
public function store()
{
$request = Request::all();
//print_r($request);
$rules = ['photo' => 'required|mimes:jpeg,bmp,png,jpg'];
$validator = Validator::make($request, $rules);
if ($validator->fails()) {
// json error
return $validator->messages()->toJson();
} else {
if (Request::hasFile('photo')) {
if (Request::file('photo')->isValid())
{
$media = new Media;
$destinationPath = base_path() . '/public/uploads';
// getting image extension
$extension = Request::file('photo')->getClientOriginalExtension();
// 如果你有裝 uuid 的話 renameing image
// 沒有則是可以自己 random 檔名,或沿用舊檔名
$fileName = Uuid::generate(4) . '_store_.' . $extension;
// move file to dest
Request::file('photo')->move($destinationPath, $fileName);
// save data
$media->src = $fileName;
$media->save();
//response success
return Response::json(array('data' => $media), 200);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment