简体   繁体   English

PHP苗条如何使用雄辩的文件上传?

[英]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 . 您正在将模型图像属性设置为\\Psr\\Http\\Message\\UploadedFileInterface类型的对象 ,而不是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 . Slim $request->getUploadedFiles()返回\\Psr\\Http\\Message\\UploadedFileInterface类型的对象,而不是字符串

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: 但是,我们将立即获取所有数据并将其设置为Model属性:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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