在这里主要写点图片上传相关的东西。
总体上也分两种情况来进行处理,第一种是laravel框架的上传方式,第二种是普通的处理方式。
首先从laravel框架的角度来讲,我们可以使用laravel框架自带的方法来进行处理图片的上传和获取问题。示例代码如下:
如下的这种方式生成缩略图的上传方式:
public function images(Request $request)
{
$file=$request->file('file');
$extension=$file->getClientOriginalExtension();
$name=uniqid().'.'.$extension;
if (!file_exists(base_path('storage').'/app/head_img/')){
mkdir(base_path('storage').'/app/head_img/',0777,true);
}
\Image::make($file)->resize(100, 100)->save(base_path('storage').'/app/head_img/'.$name);
return \Response::json([
'jsonrpc'=>'2.0',
'result'=>$name,
'id'=>url('ymzy/admin/show-ico',['fileName'=>$name])
]);
}
下面的这个是直接把原图片进行存储保存的方法:
public function images(Request $request)
{
$file=$request->file('file');
$extension=$file->getClientOriginalExtension();
$name=uniqid().'.'.$extension;
\Storage::put('head_img/'.$name,file_get_contents($file->getRealPath()));
return \Response::json([
'jsonrpc'=>'2.0',
'result'=>$name,
'id'=>url('ymzy/admin/show-ico',['fileName'=>$name])
]);
}
'local' =>[
'driver' => 'local',
'root' => storage_path('app'),
],
如上面的这种存储方法,我们可以把保存成功后的图片名字 $name保存到数据库中的图片对应的字段。那么如何如何访问到该图片呢?
laravel框架中访问该图片的方法:也就是说我们只要通过访问showIco()方法即可访问到该图片了,在这里我们只需要把数据库中保存的图片名字传递给该方法即可。
public function showIco($fileName)
{
return \Response::download(storage_path().'/app/head_img/'.$fileName,null,array(),null);
}
在这里我们定义一下上传和获取图片的路由:
Route::post('/api/v1/upload/images','UserController@images');
Route::get('/api/v1/show-ico/{fileName}','UserController@showIco');
这里写一下其他的上传图片的方法,这种方法是把图片存储到了public目录下,方便之处就是可以直接用域名加上图片保存的地址就可以访问到该图片了。
if ($request->hasFile('file_a')) {
$up_res=uploadHeadPortrait($request->file('file_a'));
if($up_res===false){
return $this->setStatusCode(6043)->respondWithError($this->message);
}else{
$file_name=$up_res;
}
}else{
return $this->setStatusCode(9999)->respondWithError($this->message);
}
function uploadHeadPortrait($file){
$filesize=$file->getClientSize();
if($filesize>2097152){
return false;
}
$entension = $file -> getClientOriginalExtension();
$mimeTye = $file -> getMimeType();
if(!in_array($mimeTye,array('image/jpeg','image/png'))){
return false;
}
$new_name=$prefix."_".time().rand(100,999).'.'.$entension;
if (!file_exists(base_path('public').'/upload/head_img/')){
mkdir(base_path('public').'/upload/orderComment/',0777,true);
}
Image::make($file)->resize(100, 100)
->save(base_path('storage').'/upload/orderComment/'.'thu_'.$new_name);
$a=$file->move(base_path('storage').'/upload/orderComment/',$new_name);
$name='/storage/upload/orderComment/'.$new_name;
return $name;
}