1

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

我将uploadedfileName 定义为全局变量。当时我上传文件后,我试图将文件名存储到这个变量中,我想用文件名在 getResponseWithPython 函数中获取全局变量

HTML:

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

我将uploadedfileName 定义为全局变量

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);
    });

};

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

4

2 回答 2

1

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

我相信它会起作用。

于 2018-05-21T10:24:56.457 回答
0

声明期间不要赋值。

**//declartion**
global.uploadedFileName;
于 2018-05-16T05:56:51.060 回答