简体   繁体   中英

PHP cURL Upload File To Node JS Server

I have a PHP frontend project and Node JS API.

I need to send a file to API but I have to use cURL, because the form send to PHP and PHP send to Node JS via cURL.

I've tried a lot of different ways, but I'm not able to get it working.

On my API I'm using multer to handle upload, and everything's working fine. I can send files from Postman or direct from the form, if I set action direct to API.

This is the last code I've tried:

$url = $this->url;
$filename = $_FILES['logo']['name'];
$filedata = $_FILES['logo']['tmp_name'];
$filesize = $_FILES['logo']['size'];

if ($filedata != '') {
    echo $filename;
    $headers = array("Content-Type:multipart/form-data"); // cURL headers for file uploading
    $postfields = array("filedata" => "@$filedata", "filename" => $filename);
    $ch = curl_init();
    $options = array(
        CURLOPT_URL => $url,
        CURLOPT_HEADER => true,
        CURLOPT_POST => 1,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_POSTFIELDS => $postfields,
        CURLOPT_INFILESIZE => $filesize,
        CURLOPT_RETURNTRANSFER => true
    ); // cURL options
    curl_setopt_array($ch, $options);
    curl_exec($ch);
    if(!curl_errno($ch)) {
        $info = curl_getinfo($ch);
        if ($info['http_code'] == 200)
            $errmsg = "File uploaded successfully";
    }
    else {
        $errmsg = curl_error($ch);
    }
    curl_close($ch);
}

Nothings' happen...

After lot of tries I managed to make it work!

This is my code:

$file = $_FILES[$inputName]['tmp_name'];

$mimetype = mime_content_type($file);

$cFile = new CURLFile($file, $mimetype);

// add file with $_POST data
$this->data[$inputName] = $cFile;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$this->url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->data);
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->header);

$result = curl_exec($ch);
curl_close($ch);

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