Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
556 views
in Technique[技术] by (71.8m points)

node.js - NodeJS: sending/uploading a local file to a remote server

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)

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.

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.

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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

After gazillion of trial-failure this worked for me. Using FormData with node-fetch. Oh, and request deprecated two days ago, btw.

const FormData = require('form-data');
const fetch = require('node-fetch');

function uploadImage(imageBuffer) {
  const form = new FormData();
  form.append('file', imageBuffer, {
    contentType: 'image/jpeg',
    filename: 'dummy.jpg',
  });
  return fetch(`myserver.cz/upload`, { method: 'POST', body: form })
};

In place of imageBuffer there can be numerous things. I had a buffer containing the image, but you can also pass the result of fs.createReadStream('/foo/bar.jpg') to upload a file from drive.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...