简体   繁体   中英

php slim how to file upload using eloquent?

I'm trying to upload an image and im using postman and the image is not being inserted in the database

this is the error

Any Suggestions on what i should do ?

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'image' cannot be null (SQL: insert into `images` (`image`) values ())

here is the route

$app->post('/images', function($request, $response, $args) {
  $data = $request->getUploadedFiles();
  $image = new Image();
  $image->image = $data['image'];
  $image->save();

  return $this->response->write($image->toJson());
});    

here is the postman page

在此处输入图片说明

and here are the headers

在此处输入图片说明

Problem

You are setting the Model image property to an object of type \\Psr\\Http\\Message\\UploadedFileInterface instead of a string . The Model does not know how to handle the object.

The Slim $request->getUploadedFiles() returns an object of type \\Psr\\Http\\Message\\UploadedFileInterface and not a string .

Solution

To access the image data, first we need to get the stream :

$data = $request->getUploadedFiles();
$uploadedImage = $data['image'];
$uploadedImageStream = $uploadedImage->getStream();

Now that we have the stream , we can read from it chunks just like we would from a file. However, we are just going to fetch all the data at once and set it to the Model property:

$image->image = $uploadedImageStream->getContents();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM