简体   繁体   中英

How to send image via form with cakephp 4 to backend via REST API?

I'm trying to send an image to a registration service made in Node.js.

I have a form made like this:

 <?= $this->Form->create($product, ['enctype' => 'multipart/form-data']); ?>
            <div class="card-body">
                <div class="row mt-3">
                    <div class="col-6">
                        <input type="file" name="file"/>
                    </div>
                </div>
            </div>
            <div class="card-footer">
                <button type="submit" class="btn btn-info">Save</button>
        </div>
    </form>
 </div>

In the controller I get the image like this:

$image = $this->request->getData("file");
debug($image);
$response = $http->post('http://localhost:8889/api/.../new/',
    [
      'file' => $image, 
    ]
);

The result is this:

object(Laminas\Diactoros\UploadedFile) id:0 {
private clientFilename => 'Captura de Tela 2023-01-02 às 18.22.54.png'
private clientMediaType => 'image/png'
private error => (int) 0
private file => '/Applications/MAMP/tmp/php/phpLuDfvm'
private moved => false
private size => (int) 1024251
private stream => null
}

My problem at the moment is that I don't receive the image in the backend. The information is received as undefined

How can I correctly send cakephp 4 image file to backend?

        // store your uploaded file in tmp folder

        // upload file
        $file = $this->request->getData('file');
        if ($file instanceof \Laminas\Diactoros\UploadedFile) {
            /** @var \Laminas\Diactoros\UploadedFile $file */
            
            if ($file->getClientFilename()) {
                $img = TMP . $file->getClientFilename();
                $path = tempnam(sys_get_temp_dir(), uniqid('file', true));
                $file->moveTo($path);
                if ($file->getError() === 0) {
                    rename($path, $img); // move tmp_file to tmp dir and save

                   // post img

                  $response = $http->post('http://localhost:8889/api/.../new/',
                  ['file' => fopen($img, 'r']);
                }
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM