NodeJS:将本地文件发送/上传到远程服务器 [英] NodeJS: sending/uploading a local file to a remote server

查看:3713
本文介绍了NodeJS:将本地文件发送/上传到远程服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Winston模块为我的离线应用创建每日日志文件。我现在需要能够通过POST(该部分已经存在)将该文件发送或上传到远程服务器

I have used the Winston module to create a daily log file for my offline app. I now need to be able to send or upload that file to a remote server via POST (that part already exists)

我知道我需要以块的形式写入文件它不会占用内存,所以我使用 fs.createReadStream 但是我似乎只得到503响应,即使只发送示例文本。

I know I need to write the file in chunks so it doesn't hog the memory so I'm using fs.createReadStream however I seem to only get a 503 response, even if sending just sample text.

编辑

我发现接收器期望数据被命名为数据。我删除了createReadSteam,因为我只能使用'application / x-www-form-urlencoded'和同步 fs.readFileSync 。如果我在php服务器上将其更改为'multipart / form-data',我将能够再次使用createReadStream,或者仅当我更改为物理上传json文件时才会使用。

I worked out that the receiver was expecting the data to be named 'data'. I have removed the createReadSteam as I could only get it to work with 'application/x-www-form-urlencoded' and a synchronous fs.readFileSync. If I change this to 'multipart/form-data' on the php server would I be able to use createReadStream again, or is that only if I change to physically uploading the json file.

过去几周我一直在学习节点,所以任何指针都会感激不尽。

I've only been learning node for the past couple of weeks so any pointers would be gratefully received.

var http = require('http'),
    fs = require('fs');

var post_options = {
    host: 'logger.mysite.co.uk',
    path: '/',
    port: 80,
    timeout: 120000,
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
}

var sender = http.request(post_options, function(res) {
    if (res.statusCode < 399) {
        var text = ""
        res.on('data', function(chunk) {
            text += chunk
        })
        res.on('end', function(data) {
            console.log(text)
        })
    } else {
        console.log("ERROR", res.statusCode)
    }
})

var POST_DATA = 'data={['
POST_DATA += fs.readFileSync('./path/file.log').toString().replace(/\,+$/,'')
POST_DATA += ']}'
console.log(POST_DATA)
sender.write(POST_DATA)
sender.end()


推荐答案

https://github.com/mikeal/request#forms 复制

var r = request.post('http://service.com/upload', function optionalCallback (err, httpResponse, body) {
  if (err) {
    return console.error('upload failed:', err);
  }
  console.log('Upload successful!  Server responded with:', body);
})
var form = r.form()
form.append('my_field1', 'my_value23_321')
form.append('my_field2', '123123sdas')
form.append('my_file', fs.createReadStream(path.join(__dirname, 'doodle.png')))

这篇关于NodeJS:将本地文件发送/上传到远程服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆