通过Laravel HTTP发送文件会导致另一端出现无法识别的文件

11dmarpk  于 2023-02-05  发布在  其他
关注(0)|答案(2)|浏览(160)

我在Laravel中尝试将图像附加到HTTP请求时遇到了一个奇怪的问题。我正在使用以下代码将文件发送到第三方API,但第三方只接收部分文件...我是否缺少一些设置...没有错误报告,我得到了一个“成功”响应;

$request = Http::withHeaders(
  [
    'Accept' => 'application/json',
  ]
)
->attach(
  'firstupload',
  Storage::get('/uploads/firstupload.jpeg'),
  'firstupload.' . Storage::mimeType('/uploads/firstupload.jpeg'),
)
->attach(
  'secondupload',
  Storage::get('/uploads/secondupload.jpeg'),
  'secondupload.' . Storage::mimeType('/uploads/secondupload.jpeg'),
)
->post(
  'https://thirdpartyapi.com/fileUpload',
  [
    'uploadType' => 'imageUpload',
  ]
);
5ktev3wc

5ktev3wc1#

您需要将标题设置为multipart/form-data

$request = Http::withHeaders(
 [
  'Accept' => 'multipart/form-data', 
 ]
)
rsl1atfo

rsl1atfo2#

问题可能出在Storage::mimeType。它返回image/jpeg。您的文件名将变为firstupload.image/jpegsecondupload.image/jpeg。并且第三方读取了您的文件名的最后一段。即jpeg。可能将它们误认为同一个文件。尝试使用pathinfo(storage_path($path), PATHINFO_EXTENSION)代替。

$request = Http::withHeaders(
  [
    'Accept' => 'application/json',
  ]
)
->attach(
  'firstupload',
  Storage::get('/uploads/firstupload.jpeg'),
  'firstupload.' . pathinfo(storage_path('/uploads/firstupload.jpeg'), PATHINFO_EXTENSION),
)
->attach(
  'secondupload',
  Storage::get('/uploads/secondupload.jpeg'),
  'secondupload.' . pathinfo(storage_path('/uploads/secondupload.jpeg'), PATHINFO_EXTENSION),
)
->post(
  'https://thirdpartyapi.com/fileUpload',
  [
    'uploadType' => 'imageUpload',
  ]
);

相关问题