在nodejs

时间:2018-05-16 05:52:21

标签: javascript node.js express nodejs-stream

我正在尝试在节点服务器上传文件。

我将uploadfileName定义为全局变量。我在那时上传文件后,我试图将文件名存储到此变量中 我想在getResponseWithPython函数中使用文件名

获取全局变量

HTML:

<form id="upload" action="/upload" method="POST" enctype="multipart/form-data">
   <input type="submit" />
</form>

我将uploadfileName定义为全局变量

JS:

** //declartion**
global.uploadedFileName = '';

//upload route
app.post('/upload', function(req, res) {

    var busboy = new Busboy({
        headers: req.headers
    });
    busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
        console.log("Context path=" + __dirname);
        var saveTo = path.join(__dirname + "/uploads", filename);

        console.log('Uploading: ' + saveTo);
        file.pipe(fs.createWriteStream(saveTo));

        ** //After I am uploading the file at that time I am trying to store file name in to this variable**
        global.uploadedFileName = filename;

    });
    busboy.on('finish', function() {
        console.log('Upload complete');
        res.writeHead(200, {
            'Connection': 'close'
        });
        res.end("That's all folks!");
    });

    return req.pipe(busboy);

});


function getResponseWithPython(prevMsg, cb) {

    ** // I want to get the global variable in this function with the file name**
    console.log(" global.uploadedFileName::: " + global.uploadedFileName);
    var pythonRes = '';
    var formData = {

        // Pass data via Streams
        input_file: fs.createReadStream(__dirname + '/GoogleHeader.csv')

    };
    process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
    var req = request.post({
        url: 'https://google.com:443/classification/',
        formData: formData
    }, function optionalCallback(err, httpResponse, body) {
        if (err) {
            return console.error('upload failed:', err);
        }
        console.log('Upload successful!  Server responded with:', body);
        pythonRes = body;

        return cb(pythonRes);
    });

};

注意:我在代码中提到了注释以了解代码流和我的要求

2 个答案:

答案 0 :(得分:1)

尝试使用process.env.uploadedFileName = '';

我相信它会奏效。

答案 1 :(得分:0)

在声明期间不要指定值。

**//declartion**
global.uploadedFileName;