2

I have a image saved on my node server. I need to send this image to API written in PHP. The api accepts file from php's $_FILES.

How can i send the file from node to PHP API so that it can read from $_FILES.

i am using npm request package for sending requests

1
  • 1
    The documentation has an example: Sending forms Commented Jul 14, 2017 at 5:27

1 Answer 1

4

You could try something like the following perhaps:

var request = require('request');
var fs = require('fs');

var data = {
  file: fs.createReadStream( '/path/to/my/image.jpg' )
};
request.post({ url:'http://example.com/upload.php', formData:data }, function callback( err, response, body ) {
    if( err ) {
        return console.error( 'Failed to upload:', err );
    }
    console.log( 'Upload successful!' );
});

Or, to create a page that allows the user to select the photo to upload

var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});

  res.write('<form action="http://example.com/upload.php" method="post" enctype="multipart/form-data">');
  res.write('<input type="file" name="usrfile" />');
  res.write('<input type="submit" />');
  res.write('</form>');

  return res.end();
}).listen(8088);

On the PHP server to handle the upload you could do this:

<?php
    /* node.js upload target ~ "upload.php" */
    if( isset( $_FILES ) ){

        /* change path to suit environment */
        $dir='c:/temp/fileuploads/1/';

        $obj=(object)$_FILES['file'];
        $name=$obj->name;
        $tmp=$obj->tmp_name;

        $result = move_uploaded_file( $tmp, $dir.$name );
        echo $result ? 'File '.$name.' ws moved to '.$dir : 'Error: Failed to save '.$name;
    }
?>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks...this worked partially for me.The image is getting captured in $_FILES. But my code fails as move_uploaded_file always returns false. there are no errors. I think it has something to do with the fact that the file is not uploaded by php. is there a sol for this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.