php - 将文件发布到 API
问题描述
我正在使用"guzzlehttp/guzzle": "6.3"
. 当我将图像发布到我的 API 时,false
当我使用它检查文件hasFile().
时得到该文件是否没有提交到我的 API?
控制器
$client = new Client();
$url = 'http://localhost:9000/api';
$path = 'app/public/images/';
$name = '94.jpeg';
$myBody['fileinfo'] = ['449232323023'];
$myBody['image'] = file_get_contents($path.$name);
$request = $client->post($url, ['form_params' => $myBody]);
$response = $request->getBody();
return $response;
API
if (!$request->hasFile('image')) {
return response()->json([
'message' => 'No file',
'photo' => $request->hasFile('image'),
'photo_size' => $request->file('image')->getSize()
]);
}
解决方案
您需要将您的添加form_params
到multipart
数组中:
// untested code
$client = new Client();
$endpoint = 'http://localhost:9000/api';
$filename = '94.jpeg';
$image = public_path('images/' . $filename);
$request = $client->post($endpoint, [
'multipart' => [
[
'name' => 'fileinfo',
'contents' => '449232323023',
],
[
'name' => 'file',
'contents' => fopen($image, 'r'),
],
],
]);
$response = $request->getBody();
return $response;
推荐阅读
- c# - 在剃刀视图中为操作 URL 设置变量是一种好习惯吗?我可以把它们放在 ViewModel 中吗?
- oracle - 从 oracle 包中检索密码
- javascript - 幻灯片中的几个模态图像
- excel - 在第一次进入单元格时触发 MsgBox,对单元格的后续更改或单击不执行任何操作
- python - Python 3 中的 writerow 总是在原始行之间写一个空行,Python2 效果很好。为什么?
- go - Fabric GO SDK 的背书政策问题
- javascript - k6 - 带有 *.crt 文件的配置文件中的 tlsAuth
- sql - 使用 WITH 子句声明和使用变量
- javascript - 随机滚动到一个长度并单击列表中的可查看元素
- c# - 如何在 Visual Studio 安装项目的启动条件下检查 .Net Core 版本