Laravel:如何将图像或文件发送到 API
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40129372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel : How to send image or file to API
提问by Code On
I have an API (created by Lumen) to save an image or file from client side.
我有一个 API(由 Lumen 创建)来从客户端保存图像或文件。
this is my API code
这是我的 API 代码
if ($request->hasFile('image')) {
$image = $request->file('image');
$fileName = $image->getClientOriginalName();
$destinationPath = base_path() . '/public/uploads/images/product/' . $fileName;
$image->move($destinationPath, $fileName);
$attributes['image'] = $fileName;
}
I already try the API in postman, and everything went well, image sucessfully uploaded.
我已经在 postman 中尝试了 API,一切顺利,图片上传成功。
What's the best practice to send image from client side (call the API), and save the image in the API project ? because my code isn't working..
从客户端发送图像(调用 API)并将图像保存在 API 项目中的最佳实践是什么?因为我的代码不起作用..
This is my code when try to receive image file in client side, and then call the API.
这是我尝试在客户端接收图像文件,然后调用 API 时的代码。
if ($request->hasFile('image')) {
$params['image'] = $request->file('image');
}
$data['results'] = callAPI($method, $uri, $params);
回答by Filip Koblański
Well the true is that you won't be able to do it without sending it by post from form.
好吧,如果不通过表单邮寄发送,您将无法做到这一点。
The alternative is to send the remote url source and download it in the API like this:
另一种方法是发送远程 url 源并在 API 中下载它,如下所示:
if ($request->has('imageUrl')) {
$imgUrl = $request->get('imageUrl');
$fileName = array_pop(explode(DIRECTORY_SEPARATOR, $imgUrl));
$image = file_get_contents($imgUrl);
$destinationPath = base_path() . '/public/uploads/images/product/' . $fileName;
file_put_contents($destinationPath, $image);
$attributes['image'] = $fileName;
}
回答by Touhid
Below simple code worked for me to upload file with postman (API):
下面的简单代码适用于我使用邮递员(API)上传文件:
This code has some validation also.
此代码也有一些验证。
If anyone needs just put below code to your controller.
如果有人需要将下面的代码放入您的控制器。
From postman: use POST method, select body and form-data, select file and use image as key after that select file from value which you need to upload.
来自邮递员:使用 POST 方法,选择正文和表单数据,选择文件并使用图像作为键,然后从您需要上传的值中选择文件。
public function uploadTest(Request $request) {
if(!$request->hasFile('image')) {
return response()->json(['upload_file_not_found'], 400);
}
$file = $request->file('image');
if(!$file->isValid()) {
return response()->json(['invalid_file_upload'], 400);
}
$path = public_path() . '/uploads/images/store/';
$file->move($path, $file->getClientOriginalName());
return response()->json(compact('path'));
}