【问题标题】:Laravel : How to send image or file to APILaravel:如何将图像或文件发送到 API
【发布时间】:2017-02-28 23:23:25
【问题描述】:

我有一个 API(由 Lumen 创建)来从客户端保存图像或文件。

这是我的 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;
}

我已经在 postman 中试用了 API,一切顺利,图片上传成功。

从客户端发送图像(调用 API)并将图像保存在 API 项目中的最佳做法是什么? 因为我的代码不起作用..

这是我尝试在客户端接收图像文件,然后调用 API 时的代码。

if ($request->hasFile('image')) {
    $params['image'] = $request->file('image');
}

$data['results'] = callAPI($method, $uri, $params); 

【问题讨论】:

  • 要保存图片吗?
  • 是的,发送图片到API,保存到API公用文件夹中
  • 一个选项是以 base 64 编码文件并通过 POST 发送。但是您需要更改“服务器”代码源
  • 为此,您需要使用base64对其进行解码,然后才能将其保存在公共文件夹中。

标签: php api laravel lumen


【解决方案1】:

下面的简单代码可以让我使用邮递员 (API) 上传文件:

这段代码也有一些验证。

如果有人需要,只需将以下代码放入您的控制器。

来自邮递员:使用 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'));
 }

【讨论】:

    【解决方案2】:

    事实上,如果不通过表单邮寄,您将无法做到这一点。

    另一种方法是发送远程 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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-01
      • 1970-01-01
      • 2021-09-13
      • 2020-05-26
      • 2021-02-04
      • 2021-04-17
      • 2013-02-28
      • 2019-09-15
      相关资源
      最近更新 更多