Home > Software design >  Sending files through Laravel HTTP is resulting in unrecognised files on the other end
Sending files through Laravel HTTP is resulting in unrecognised files on the other end

Time:02-04

I am having a strange issue when trying to attach images to a HTTP request in Laravel. I am using the following code to send a file to a 3rd party api, but the 3rd party is only receiving partial files ... Am i missing some settings ... There are no errors being reported and I am getting a 'successful' response;

$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',
  ]
);

CodePudding user response:

You need to set the header to multipart/form-data

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

CodePudding user response:

The issue maybe in Storage::mimeType. It returns image/jpeg. Your file name will become firstupload.image/jpeg and secondupload.image/jpeg. And the thirdparty read the last segment of your file names. i.e. jpeg. Maybe mistaking them for the same file. Try to use pathinfo(storage_path($path), PATHINFO_EXTENSION) instead.

$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',
  ]
);
  • Related