在上传

时间:2016-08-17 20:20:03

标签: javascript ajax node.js file-upload

我有一个Node.js服务器端脚本,可以成功上传"某些东西"到指定的目录。但这不是我选择的文件和脚本错误说明:

 Request received: POST
 undefined:1
 ------WebKitFormBoundary1urLweAWe6T1VpEA
 ^

SyntaxError: Unexpected number
at Object.parse (native)
at IncomingMessage.<anonymous> (C:\Users\gcampbell\De
p.js:51:33)
at emitOne (events.js:82:20)
at IncomingMessage.emit (events.js:169:7)
at readableAddChunk (_stream_readable.js:153:18)
at IncomingMessage.Readable.push (_stream_readable.js
at HTTPParser.parserOnBody (_http_common.js:124:22)

这是我在上传目录中最终得到的文件。

upload_3b2ab28a59131c95015a90a4afe972cd

这是 NODE.JS 应用的一部分:

var http = require('http');
var fs = require('fs');
var path = require('path');
var formidable = require('formidable');
var fs = require('fs');

http.createServer(function(req, res) {

    console.log('Request received: ' + req.method);

    if (req.method == 'GET') {
        fs.readFile("comments-data.json", 'utf8', function(err, data) {
            if (err) {
                return console.log(err);
            } else {
                res.setHeader("Content-Type", "text/json");
                res.setHeader("Access-Control-Allow-Origin", "*");
                res.end(data)
            }
        })
    };
    if (req.method == 'POST') {
            // create an incoming form object
          var form = new formidable.IncomingForm();

          // specify that we want to allow the user to upload multiple files in a single request
          form.multiples = true;

          // store all uploads in the /uploads directory
          form.uploadDir = path.join(__dirname, '/uploads');

          // every time a file has been uploaded successfully,
          // rename it to it's orignal name
          form.on('file', function(field, file) {
            fs.rename(file.path, path.join(form.uploadDir, file.name));
          });

          // log any errors that occur
          form.on('error', function(err) {
            console.log('An error has occured: \n' + err);
          });

          // once all the files have been uploaded, send a response to the client
          form.on('end', function() {
            res.end('success');
          });

          // parse the incoming request containing the form data
          form.parse(req);
        req.on('data', function(chunk) {
            var element = JSON.parse(chunk);
            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"}');
        });
    };

这是 AJAX 电话:

                uploadAttachments: function(commentArray, success, error) {
                        var responses = 0;
                        var successfulUploads = [];

                        var serverResponded = function() {
                            responses++;

                            // Check if all requests have finished
                            if(responses == commentArray.length) {

                                // Case: all failed
                                if(successfulUploads.length == 0) {
                                    error();

                                // Case: some succeeded
                                } else {
                                    success(successfulUploads)
                                }
                            }
                        }

                        $(commentArray).each(function(index, commentJSON) {

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

                            $.ajax({
                                url: 'http://localhost:8080',
                                type: 'POST',
                                data: formData,
                                cache: false,
                                contentType: false,
                                processData: false,
                                success: function(commentJSON) {
                                    successfulUploads.push(commentJSON);
                                    serverResponded();
                                },
                                error: function(data) {
                                    serverResponded();
                                },
                            });
                        });
                    }

这应该接受POST,存储文件并更新comments-data.json文件中的JSON数据,以指定新文件的去向。

提前致谢!

ajax请求是一个回调函数,用于将附件上传到服务器。回调的第一个参数是commentArray,包括作为注释模型的所有附件,其中file字段包含要上载的文件。服务器应在fileURL字段中返回上载文件的URL。回调提供成功和错误回调,应根据服务器的结果调用回调。成功回调会将一系列成功上传作为参数。

1 个答案:

答案 0 :(得分:0)

错误undefined:1通常意味着您尝试解析不正确的JSON。解析非安全数据时始终使用try-catch,例如通过浏览器。

req.on('data', function(chunk) {
   var element; 
   try {
       element = JSON.parse(chunk);
   } catch(err) {
       return // res status 500, console.log(err), smth-else
   }

   fs.readFile("comments-data.json", 'utf8', function(err, json) {
       // here safety data
       var array = JSON.parse(json);
       array.push(element);
       fs.writeFile("comments-data.json", JSON.stringify(array), function(err) {
           if (err) 
               return console.log(err);

           console.log("The file was saved!");
        });
    });
});

尝试通过

从表单获取数据
$.ajax({
    type: 'POST',
    url: '/',
    data: new FormData($('#your-form-id')[0]),
    processData: false,
    ...