skip to Main Content

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

2

Answers


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

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

    UPDATE:

    I think your code is just fine but you need to do the following

    replace Storage::get(‘/uploads/firstupload.jpeg’), with file_get_contents("storage/path/uploads/firstupload.jpeg"),

    event though your Accept is also okay it can be application/json

    Login or Signup to reply.
  2. 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',
      ]
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search