通过第三方软件上传文件到 S3 存储桶

时间:2021-05-14 10:34:48

标签: php amazon-s3 curl

所以我正在一个有 Web2Print 设计器的 WordPress 网站上工作,我正在尝试在该设计器之上实现删除背景功能。基本上我从 Web2Print 抓取图像,将其发布到 API 并接收去除背景的图像。 Web2Print 的开发者说我需要将图像上传到他们的 S3 存储桶,然后将 URL(s3 存储桶文件)发送回 Web2Print 并将其放置在应用程序中的画布上。

在 Web2Print 中我可以做到这一点

let _comm = Box.Application.getService('comm');
_comm.post('upload/', { contentType: 'image/png', ext: 'png', rawPath: 'assets/' }) 
.then(_data => {...});

如果我控制台日志 _data 我得到以下内容

fields: 
  Key: "raw/<SOME HASH>.png"
  Policy: "<SOME OTHER HASH>"
  X-Amz-Algorithm: "AWS4-HMAC-SHA256"
  X-Amz-Credential: "<SOME HASH>/20210514/eu-west-1/s3/aws4_request"
  X-Amz-Date: "20210514T094324Z"
  X-Amz-Security-Token: "<SOME HASH>"
  X-Amz-Signature: "<SOME HASH>"
  bucket: "<BUCKET NAME>"
url: "<URL>"

所以我需要在 curl 中执行 php 将图像上传到 s3 存储桶。这就是我需要帮助的地方,看起来我有我需要做的一切。为了让 curl 正常工作,我已经让这个家伙的例子休息了。

https://www.h3xed.com/programming/php-amazon-s3-file-upload-code-aws-signature-version-4

我已经验证我已经正确地传递了 _data 对象中的所有变量。所以,这是我的 curl 代码。

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
  'Content-Type' =>  "image/png",
   // 'acl' => '',
  'Key' => $key,
  'Policy' =>  $policy,
  'X-Amz-Algorithm' => 'AWS4-HMAC-SHA256',
  'X-Amz-Credential' => $credential,
  'X-Amz-Sate' => $bucketDate,
  'X-Amz-Aignature' => $signature,
  'X-Amz-Security-Token' => $security_token, 
  'file' => new CurlFile(realpath($imageRemoveBackgroundUrl), "image/png", 'no-bg.png')
]);

$response = curl_exec($ch);

$staus_code;
$error_log = curl_errno($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) == 204) {
  echo 'Success!';
  $status_code = 204;
} else {
  $error = substr($response, strpos($response, '<Code>') + 6);
  echo substr($error, 0, strpos($error, '</Code>'));
  $status_code = substr($error, 0, strpos($error, '</Code>'));
}
curl_close($ch);

注意:$imageRemoveBackgroundUrl 是一个 avlid ULR 字符串

这段代码什么也没给我。如果我运行 curl_getinfo($ch, CURLINFO_HTTP_CODE),我会得到空字符串,如果我运行 curl_error($ch) 我也会得到空字符串,如果我运行 curl_errno($ch) 我也会得到空字符串。

如果我替换这行代码 'file' => new CurlFile(realpath($imageRemoveBackgroundUrl), "image/png", 'no-bg.png') 有了这个 'file' => $imageRemoveBackgroundUrl 我在 InvalidArgument 得到 responseText

我也试过这个没有用'x-amz-content-sha256' => hash('sha256', file_get_contents($imageRemoveBackgroundUrl)),仍然得到无效的论点。

Web2Print 公司的技术支持人员说我需要将整个 _data 对象传递给 curl 而不以任何方式更改它,所以我这样做了,但我收到了这个错误 {{ 1}},但我认为这行不通,因为我需要上传 PreconditionFailed 对象不知道的文件。

那么我想做的事情有可能吗?

0 个答案:

没有答案
相关问题