如何在API中使用lumen laravel发布和获取图像?



我有这个数据库

return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('post', function (Blueprint $table) {
$table->bigIncrements('id'); 
$table->string('title', 100) -> nullable();
$table->text('content', 300)-> nullable();
$table->string('image', 100)-> nullable();
$table->string('phone', 300)-> nullable();
$table->string('coordinates', 300)-> nullable();
$table->string('website', 300)-> nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('post');
}
};

我想发布并获取图像,唯一让我困惑的是,如何获取我发布的图像,我已经在我的API中调用了它,但结果是404,我已经将其上传到了web服务上http://lovemonster.my.id/hospital只要看看&点击图片部分,它显示错误,这是我的控制器:

class HospitalController extends Controller
{
public function create(Request $request)
{
$data = $request->all();
$hospital = Hospital::create($data);
return response()->json($hospital);
}
public function index()
{
$hospital = Hospital::all();
return response()->json($hospital);
}
} 

这是我的型号:

class Hospital extends Model
{
protected $table = 'post';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'title','content','image', 'phone', 'coordinates', 'website'
];
} 

如何获得我存储的图像,我的控制器上的代码是什么样子的,如果你知道如何做到这一点,请让我知道,因为我对lumen和laravel 很陌生

对于post请求,您需要将图像保存在公共或存储文件夹中,并在db中为图像添加该路径。

class HospitalController extends Controller
{
public function create(Request $request)
{
// upload image
$filename = $this->getFileName($request->image);
$request->image->move(base_path('public/images'), $filename);

$hospital = new Hospital(request()->except('image'));
$hospital->image = $filename;
$hospital->save();
return response()->json($hospital);
}

protected function getFileName($file)
{
return str_random(32) . '.' . $file->extension();
}
public function index()
{
$hospital = Hospital::all();
return response()->json($hospital);
}
} 

您的模型Hospital.php

class Hospital extends Model
{
protected $table = 'post';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'title','content','image', 'phone', 'coordinates', 'website'
];
// this function will give your full image URL in records
public function getImageAttribute($value)
{
return env('APP_URL').$value;
}
}

在.env中,使用您的项目域名设置APP_URL,如https://www.project.com/

最新更新