在Node.js中发送表单数据

时间:2019-02-25 06:23:22

标签: node.js multipartform-data

问题不同,我找不到任何问题 问题是关于通过纯Node.js中的多部分表单数据发送文件。

使用reference

我丢失了一些东西,强大的功能在服务器端抛出了一个错误,一些解析器错误。

  

err错误:解析器错误,已解析44个字节中的0个       在IncomingForm.write

var boundary = "AaB03x";
var boundary2 = "BbC04y";

var http = require("http");
var fs = require("fs");
var config = require("../../config");
var files = [
    __dirname + "/../../../../assets/Watch/a.txt",
    __dirname + "/../../../../assets/Watch/b.txt",
];

var request = http.request({
    hostname: 'localhost',
    path: '/' + config.watch,
    method: 'POST',
    port: 50412,
    headers: {
        'accept': 'application/json;charset=UTF-8',
        'content-type': 'multipart/form-data; boundary=' + boundary,
    }
}, function(response){
    var buffers = [];
    response.on('data', buffers.push.bind(buffers));
    response.on('end', function(){
        try {
            var body = Buffer.concat(buffers).toString();
            if(response.statusCode == 200) {
                console.log(JSON.parse(body));
                done();
            } else {
                console.error(response.statusCode, body);
            }
        } catch(error) {
            console.log("catch ", error);
            console.error(error);
        }

    });
}).on('error', function(error){
    console.log("main error", error);
});


request.write("Content-Type: multipart/form-data; boundary=" + boundary);
request.write("\r\n\r\n");

request.write("--" + boundary);
request.write('Content-Disposition: form-data; name="files"');
request.write('Content-Type: multipart/mixed; boundary=' + boundary2);
request.write("\r\n\r\n");

request.write("--" + boundary2);
request.write('Content-Disposition: file; filename="a.txt"');
request.write('Content-Type: text/plain');
request.write("\r\n\r\n");

var readStream1 = fs.ReadStream(files[0]);
readStream1.on('error', function(){
    console.log("1 error");
});
readStream1.on('end', function(){
    console.log("1 end");

    request.write("--" + boundary2);
    request.write('Content-Disposition: file; filename="b.txt"');
    request.write('Content-Type: text/plain');
    request.write("\r\n\r\n");

    var readStream2 = fs.ReadStream(files[1]);
    readStream2.on('error', function(){
        console.log("2 error");
    });
    readStream2.on('end', function(){
        console.log("2 end");
        request.end();
    });
    readStream2.on('close', function(){
        console.log("2 close");
        request.write("--" + boundary2 + "--");
        request.write("--" + boundary + "--");
        request.end();
    });
    readStream2.pipe(request);

});
readStream1.on('close', function(){
    console.log('1 close');
});
readStream1.pipe(request);

0 个答案:

没有答案