使用request或axios nodejs将文件上载到另一台服务器

时间:2017-08-04 22:12:20

标签: node.js

我有一个用户表单,用户可以在其中选择系统上的文件,然后使用FormData将其上传到另一台服务器。测试直接发送到api时,它工作正常。但我需要在发送之前修改标头。所以我发布到客户端应用程序的后端。

router.post('/upload', function(req, res, next) {
  //...some axios or request logic

  var fs = require('fs');
  var request = require('request');
  var formData = {
    my_field: 'my_value',
    my_file: fs.createReadStream(__dirname + '/example.doc'),
  };

  request.post({url:'http://someothereapp/upload-file', formData: formData}, function(err, httpResponse, body) {
    if (err) {
      return console.error('upload failed:', err);
    }
    console.log('Upload successful!  Server responded with:', body);
    res.send('good!');
  });

});

axiosrequest非常适合发布普通表单或获取请求。但是,当我尝试使用它来发送文件时,它不起作用。上面的代码总是返回成功但不上传文件。所以我去here但仍然不太了解我错过了什么。

我在测试时在其他服务器(本地)上关闭了身份验证和跟踪,因此我不必修改标头。它具有以下代码,如果我从Web表单直接将文件发送到它,但不是从我的客户端快速应用程序发送,它可以正常工作:

  // http://someothereapp/upload-file
  router.post('/upload-file', (req, res, next) => {
    let multer = require('multer')
    let p =  path.join(__dirname, '../uploads');
    let storage = multer.diskStorage({
      destination: function(req, file, callback) {
        callback(null, p )
      },
      filename: function(req, file, callback) {
        console.log('what is file', file)
        callback(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
      }
    })

    let upload = multer({
      storage: storage
    }).single('userFile')
    upload(req, res, function(err) {
      res.end('File is uploaded')
    })
  });

我看到了this问题,并认为这可能意味着axios不可能,但你如何处理请求呢?例如,在post ... upload代码中,如何将my_file作为用户在其表单中选择的文件?为什么即使它没有上传文件也没有失败?

1 个答案:

答案 0 :(得分:1)

我将客户端后端应用更改为以下内容,它允许我修改标题并发送表单:

router.post('/upload-file', function(req, res, next) {
  var httpProxy = require('http-proxy');
  var proxy = httpProxy.createProxyServer({headers: customHeader});
  proxy.web(req, res, { target: 'http://someothereapp' }, function(e) { 
    // will proxy request to http://someothereapp/upload-file
    ...
  });
});

客户表格(未更改):

<form name='uploadfile'  enctype="multipart/form-data" method="post">
  <input type="file" name="userFile" />
  <input type="submit" value="Upload File" name="submit">
</form>


<script>
var form = document.forms.namedItem("uploadfile");
form.addEventListener('submit', function(ev) {

  var oOutput = document.querySelector("div"),
      oData = new FormData(form);

  var oReq = new XMLHttpRequest();
  oReq.open("POST", "/upload-file", true);
  oReq.onload = function(oEvent) {
    if (oReq.status == 200) {
      // oOutput.innerHTML = "Uploaded!";
      console.log('Uploaded');
    } else {
      console.log('error', oReq.status);
      // oOutput.innerHTML = "Error " + oReq.status + " occurred when trying to upload your file.<br \/>";
    }
  };

  oReq.send(oData);
  ev.preventDefault();
}, false);
</script>

目标服务器(未更改):

  // http://someothereapp/upload-file
  router.post('/upload-file', (req, res, next) => {
    let multer = require('multer')
    let p =  path.join(__dirname, '../uploads');
    let storage = multer.diskStorage({
      destination: function(req, file, callback) {
        callback(null, p )
      },
      filename: function(req, file, callback) {
        console.log('what is file', file)
        callback(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
      }
    })

    let upload = multer({
      storage: storage
    }).single('userFile')
    upload(req, res, function(err) {
      res.end('File is uploaded')
    })
  });