Send multiple files via PHP curl to Spring Boot API

33 Views Asked by At

I want so send multiple uploaded files from my PHP application via curl to my Spring Boot API.

My API is defined like this:

@PostMapping(consumes = {"multipart/form-data"})
public MyApiResponse createOrUpdate(@RequestPart("data") MyDataDto myDataDto,
    @RequestPart(value = "images", required = false) MultipartFile[] images) {
    ...
}

Which means that i can possibly upload multiple files.

I tried my API with Postman and it works fine. enter image description here

So now i want to use this API in my PHP application with the following code:

First approach

function uploadFiles($data, $fileInputName, $url) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_POST, 1);
    
    $postFields = array();
    
    // Convert data to file
    $tempFile = tmpfile();
    fwrite($tempFile, json_encode($data));
    $tempFilePath = stream_get_meta_data($tempFile)['uri'];
    $postFields["data"] = curl_file_create($tempFilePath, "application/json");
    
    // Pack image for sending
    $countFiles = count($_FILES[$fileInputName]["size"]);
    $j = 0;
    for ($i = 0; $i < $countFiles; $i++) {
        if ($_FILES[$fileInputName]['size'][$i] == 0) {
            continue;
        }
        $postFields["images[".$j++."]"] = curl_file_create(
            $_FILES[$fileInputName]['tmp_name'][$i],
            $_FILES[$fileInputName]['type'][$i],
            $_FILES[$fileInputName]['name'][$i]
        );
    }

    curl_setopt($curl, CURLOPT_POSTFIELDS, $postFields);
    
    curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: multipart/form-data"));
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    
    $result = curl_exec($curl);
    curl_close($curl);
    unset($curl);
    return $result;
}

With this solution zero images are received in my API.

Second approach

I also tried collecting my curl_files in another array

        $images[] = curl_file_create(
            $_FILES[$fileInputName]['tmp_name'][$i],
            $_FILES[$fileInputName]['type'][$i],
            $_FILES[$fileInputName]['name'][$i]
        );

and set it as $postFields["images"] = $images but this didn't work either.

Third approach

The only thing that worked so far was to set one single file to the key "images"

        $postFields["images"] = curl_file_create(
            $_FILES[$fileInputName]['tmp_name'][0],
            $_FILES[$fileInputName]['type'][0],
            $_FILES[$fileInputName]['name'][0]
        );

But i clearly want to send multiple Files. :(

So how can i manage to send multiple curl_files with the same key "images"?

0

There are 0 best solutions below