Evelyn Woodley
Evelyn Woodley

Reputation: 35

node https module send file to php server

How to send HTTP post request that include a jpg file to php server with node https module? I tried using request module but its unreliable (timed out most of the time) and its already deprecated.

This is my node upload function

function uploadScreen() {
var data = querystring.stringify({file: fs.createReadStream( path.join( os.tmpdir() , 'screen.jpg' ) )});
var header = {'Content-Type': 'image/jpg','Content-Length': data.length, 'User-Agent': 'Mozilla/5.0 ' + os.type() + ' Client','X-Requested-With': global.id};
var server = {hostname: 'server.net', port: 443, path: '/upload.php', method: 'POST', headers:header};
var req = https.request(server, (res) => {
    console.log('statusCode:', res.statusCode);
    console.log('headers:', res.headers);
    res.on('data', (d) => {process.stdout.write(d);});
});
req.on('error', (e) => {console.error(e);});
req.write(data);
req.end();
}

I receive it with my php server like this

<?php
$target_dir = "../";
$obj=(object)$_FILES['file'];
$userid = $_SERVER['HTTP_X_REQUESTED_WITH'];
$name=date("Ymd")."-".$userid."-".date("His").".jpg";
$tmp=$obj->tmp_name;


move_uploaded_file($tmp, $target_dir.$name);
?>

My php server return HTTP 200 to my node client but with no files uploaded. All the header were sent correctly but the body doesn't. According to my access.log the server only receive 5 bytes of data. The weird thing is, this is working with the old deprecated request module although unreliably.

Upvotes: 1

Views: 184

Answers (1)

NeNaD
NeNaD

Reputation: 20374

You can use axios HTTP client.

https://www.npmjs.com/package/axios

You can modify your code like this:

const axios = require('axios');

...

async function uploadScreen() {
  try {
    let image = fs.readFileSync(path.join(os.tmpdir(), 'screen.jpg'));
    let sending_image_result = await axios({
       method: 'post',
       url: 'https://server.net:443/upload.php',
       data: {
         file: image 
       },
       headers: {
         'Content-Type': 'image/jpg',
       },
    });
    //Image is send
    console.log('Result: ', sending_image_result);
  } catch (error) {
    console.log('Error: ', error);
  }
}

Upvotes: 1

Related Questions