Nodejs send server files to server

Asked

Viewed 229 times

0

Good afternoon, my friends, I am trying to send a file from an application of mine (in Node) to a web server made in PHP. But it is returning the message saying that the file parameter (arqCsv) was not found. In the documentation-driven example, they use Curl in PHP:

$ipServidor      = '192.168.0.1' 
$arquivo         = '/tmp/arquivo.csv'; 
$campos          = 'idext:cpf:nome'; 
$idIntegracao    = 0;
$pularBLS        = 0; 
$incremental     = 0; 
$ativaAoImportar = 0; 

$post = array(
    'arqCsv'       => '@'.$arquivo, // No cURL, o '@' significa Envio de Arquivo.
    'campos'       => $campos,
    'idintegracao' => $idIntegracao,
    'pularBLS'     => $pularBLS,
    'incremental'  => $incremental,
    'ativar'       => $ativaAoImportar
    );

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,  "http://$ipServidor/software/servicos/importar.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result = curl_exec ($ch);
curl_close ($ch);

Since I have done several tests on my system to send the file, both using the module Request, Module Form-Data and the module Restler.

Following is an example of code using the Restler Module.

SendFile(fileName, campos, idintegracao) {
		return new Promise((res, rej) => {
			console.log(`Localizando arquivo ${fileName}`)
			//Funciona perfeitamente, mas nao ve o arquivo.

			fs.stat(fileName, function(err, stats) {
				restler.post("http://servico.com/aplicacao/servicos/importar.php", {
					multipart: true,
					data: {
						"idintegracao": idintegracao,
						"campos": campos.toString().split(',').join(':'),
						"arqCsv": restler.file(fileName, null, stats.size, null, "text/csv")
					}
				}).on("complete", function(data) {
					console.log(data);
					res(data)
				});
			});
			return ;
   });
})

1 answer

0


You can use the module request, more specifically the sending of Forms as follows:

const request = require('request');
const fs = require('fs');
const path = require('path');

const enviar = (campos, idintegracao) => {
  return new Promise((resolver, rejeitar) => {
    const formData = {
      idintegracao,
      ...campos,
      arqCsv: fs.createReadStream(path.join(__dirname, '/tmp/arquivo.csv')),
    };

    request.post({ url: 'http://servico.com/aplicacao/servicos/importar.php', formData }, function callback (erro, resposta, body) {
      if (erro) return rejeitar('Envio falhou:', erro);
      resolver('Enviado com sucesso! O servidor respondeu:', body);
    });
  });
};

module.exports = {
  enviar,
};

Browser other questions tagged

You are not signed in. Login or sign up in order to post.