我需要将AJAX调用分开来做两件事

时间:2016-08-18 20:46:35

标签: jquery json node.js express formidable

我需要我的ajax调用才能发送两个单独的调用。一个用于文件,一个用于JSON数据。然后,我试图让NODE.JS上传文件,返回目标和服务器端JSON数据内部。

这是我的 AJAX

                uploadAttachments: function(commentArray, success, error) { 

                    $(commentArray).each(function(index, commentJSON) {
                    console.log(commentJSON.File);
                    $.ajax({
                        type: 'post',
                        url: 'http://localhost:8080',
                        data: commentJSON.file + JSON.stringify(commentJSON),
                        success: function(commentJSON) {
                            success(commentJSON)
                        },
                        error: error
                    });
                    });
                }

这是我的 NODE

    if (req.method == 'POST') {
        // get the temporary location of the file
        var tmp_path = req.files.thumbnail.path;
        // set where the file should actually exists - in this case it is in the "images" directory
        var target_path = '/uploads' + req.files.thumbnail.name;
        // move the file from the temporary location to the intended location
        fs.rename(tmp_path, target_path, function(err) {
            if (err) throw err;
            // delete the temporary file, so that the explicitly set temporary upload dir does not get filled with unwanted files
            fs.unlink(tmp_path, function() {
                if (err) throw err;
                res.send('File uploaded to: ' + target_path + ' - ' + req.files.thumbnail.size + ' bytes');
            });
        });
        req.on('data', function(chunk) {
               var element; 
               try {
                   element = JSON.parse(chunk);
               } catch(err) {
                   console.log(err);
               }
            fs.readFile("comments-data.json", 'utf8', function(err, json) {
                var array = JSON.parse(json);
                array.push(element);
                fs.writeFile("comments-data.json", JSON.stringify(array), function(err) {
                    if (err) {
                        console.log(err);
                        return;
                    }
                    console.log("The file was saved!");
                });
            });
            res.end('{"msg": "success"}');
        });
    };

我尝试了几种不同的变体和备用脚本。我的部分问题是,这是使用JQuery插件。我不明白应该如何发送数据。

文档说的是这样的:

        // Create form data
        var formData = new FormData();
        $(Object.keys(commentJSON)).each(function(index, key) {
            var value = commentJSON[key];
            if(value) formData.append(key, value);
        });

但我不知道如何使用node.js解析它并将其拆分。

0 个答案:

没有答案