NodeJS:将本地文件发送/上传到远程服务器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19818918/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NodeJS: sending/uploading a local file to a remote server
提问by sidonaldson
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)
我使用 Winston 模块为我的离线应用程序创建了每日日志文件。我现在需要能够通过 POST 将该文件发送或上传到远程服务器(该部分已经存在)
I know I need to write the file in chunks so it doesn't hog the memory so I'm using fs.createReadStreamhowever I seem to only get a 503 response, even if sending just sample text.
我知道我需要分块写入文件,这样它就不会占用内存,所以我使用fs.createReadStream但是我似乎只得到 503 响应,即使只发送示例文本。
EDIT
编辑
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.
我发现接收者希望数据被命名为“数据”。我已经删除了 createReadSteam 因为我只能让它与 'application/x-www-form-urlencoded' 和同步fs.readFileSync 一起工作。如果我在 php 服务器上将其更改为“multipart/form-data”,我将能够再次使用 createReadStream,或者只有当我更改为物理上传 json 文件时。
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()
回答by waqas
copied from https://github.com/mikeal/request#forms
复制自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')))
回答by kub1x
After gazillion of trial-failure this worked for me. Using FormDatawith node-fetch. Oh, and requestdeprecated two days ago, btw.
在无数次试验失败之后,这对我有用。将FormData与node-fetch 一起使用。哦,顺便说一句,两天前不推荐使用请求。
const FormData = require('form-data');
const fetch = require('node-fetch');
function uploadImage(imageBuffer) {
const form = new FormData();
form.append('file', imageFileBuffer, {
contentType: 'image/jpeg',
filename: 'dummy.jpg',
});
return fetch(`myserver.cz/upload`, { method: 'POST', body: form })
};

