在网站开发中图片上传的功能很常见,这里把我写的一个图片上传功能的代码分享一下,很简单。
首先是数据库部分,为了存放网站中所有的图片,这里单独写一个数据表来存放信息。
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Schema;
class CreateImageTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
//
Schema::create('images',function(Blueprint $table){
$table->increments('id')->index();
$table->integer('user_id')->unsigned();
$table->integer('page_id')->unsigned();
$table->string('path');
$table->foreign('user_id')->references('id')->on('users');//外键
$table->foreign('page_id')->references('id')->on('page');//外键
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
Schema::drop('images');
}
}
下面是model部分
namespace App;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
//
protected $table="images";
protected $fillable=['user_id','path'];
public $timestamps=false;//不希望model自动维护create_at public_at字段
}
上传的前端代码,注意要填写<code>enctype="multipart/form-data"</code>
<form action="{{url('/image/upload')}}" role="form" method="POST" name="loginForm" enctype="multipart/form-data">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="file" name="file">
<input type="submit" value="submit">
</form>
控制器部分
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\File;
use App\Http\Requests;
use App\Image;
use Illuminate\Support\Facades\Response;
class imgageController extends Controller
{
//
public function show($imgName){
}
public function upload(Request $request,$direc){
$message="123";
$validator=Validator::make($request->all(),[
'file'=>'required|image'
] );
if($validator->fails()){
/*Response::json([
'success'=>false,
'message'=>$validator->errors()
]);*/
}else{
$file=$request->file('file');//获取文件
$fileName=md5(time().rand(0,10000)).'.'.$file->getClientOriginalName();//随机名称+获取客户的原始名称
$savePath = $direc.$fileName;//存储到指定文件,例如image/.filename public/.filename
Storage::put($savePath,File::get($file));//通过Storage put方法存储 File::get获取到的是文件内容
if(Storage::exists($savePath)){
$user=Auth::user();
Image::create([
'user_id'=>$user->id,
'path'=>$savePath
]);
}
}
}
}