我需要一些帮助。我正在Laravel中以JSON形式创建注册和登录API。我将数据发布到数据库中,数据库接收我发送的数据。但是我希望数据库以JSON格式发送响应,我也希望在Postman中选择一个文件并选择图像,那么如何将图像的URL保存在目录中呢?
到目前为止,这是我的代码......
UserController.php :
public function signup(Request $request)
{
$this->validate($request, [
]);
$user = new User([
'name' => $request->input('name'),
'email' => $request->input('email'),
'password' => bcrypt($request->input('password')),
'user_name' => $request->input('user_name'),
'profile_discription' => $request->input('profile_discription'),
'profile_pic' => $request->input('profile_pic'),
'phone_number' => $request->input('phone_number'),
'location' => $request->input('location')
]);
$user->save();
return response()->json(['Message' => 'Successfully Created User!'], 201);
web.php :
Route::post('/user/signup', ['uses' => 'UserController@signup']);
答案 0 :(得分:0)
首先使用Response Class,
use Response;
public function signup(Request $request)
{
$this->validate($request, [
]);
$user = new User([
'name' => $request->input('name'),
'email' => $request->input('email'),
'password' => bcrypt($request->input('password')),
'user_name' => $request->input('user_name'),
'profile_discription' => $request->input('profile_discription'),
'profile_pic' => $request->input('profile_pic'),
'phone_number' => $request->input('phone_number'),
'location' => $request->input('location')
]);
$user->save();
$response = array('message'=>'Successfully Created User!');
return Response::json($response);
我希望它有所帮助,
答案 1 :(得分:0)
您需要使用某些功能将文件/图像存储到某个路径,然后将路径存储到数据库。
<?php
// Folder in public/upload/
$destinationPath = "upload/";
if ($request->hasFile('profile_pic') && $request->file('profile_pic')->isValid()) {
// store file to local
$file = $request->file('profile_pic');
$ext = $file->guessExtension();
$name = $file->getClientOriginalName();
// Move file to your path
$result = $request->file('profile_pic')->move($destinationPath, $now . $name);
$finalPath = $destinationPath . '/' . $now . $name;
/*
* Save to database code continue here ...
*/
}
或者只是简单地将图像转换为BASE64
$data = $request->file('profile_pic');
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
/*
* Save to database code continue here ...
*/