NodeJS:处理文件上传的问题

时间:2014-09-11 19:05:58

标签: node.js file-upload

我不知道该写什么作为标题,因为我有一个非常奇怪的问题。我想要做的是上传并保存服务器上的* .html文件。以下是代码结构:

翡翠模板(表格):

#template-uploader
    form(enctype='multipart/form-data')
        input(name='file', type='file')
        input#upload-template(type='button', value='Upload')

JS(表格处理):

//Upload Btn Click Event Handler
$('#upload-template').on('click', function(){
    event.stopPropagation();
    event.preventDefault();

    uploadFiles();
});

// Upload the files using AJAX
function uploadFiles()
{
    var formData = $('input[type=file]')[0].files;

    $.ajax({
        url: 'template/upload',
        type: 'POST',
        xhr: function() {  // Custom XMLHttpRequest
            var myXhr = $.ajaxSettings.xhr();
            if(myXhr.upload){
                // For handling the progress of the upload
            }
            return myXhr;
        },
        data: formData[0],
        cache: false,
        processData: false, // Don't process the files
        contentType: false, // Set content type to false as jQuery will tell the server its a query string request
        success: function(data, textStatus, jqXHR)
        {
            console.log('Data');
            console.log(data);
            if(typeof data.error === 'undefined')
            {
                // Success so call function to process the form
            }
            else
            {
                // Handle errors here
                console.log('ERRORS: ' + data.error);
            }
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            // Handle errors here
            console.log('ERRORS: ' + errorThrown);
            // STOP LOADING SPINNER
        }
    });
}

服务器(Node.js)

//Route handler for template file uploaded
router.post('/template/upload', function(req, res) {
    console.log('Uploading Files');
    console.log(req.files);
});

现在的问题是,当我选择一个文件并单击上传按钮时,会发出一个ajax请求。我已经记录了我发送的数据,并且在客户端看起来很好。然而,在服务器端存在两个问题。

  1. (问题通过@Scimonster回答解决)我在req.files param中看不到任何文件。我之前在Express 3.x中做过这个,没有任何问题。现在我正在使用Express 4.x,也许我错过了一些东西。
  2. 第二个问题是,当请求发送到服务器时,终端会立即记录console.log('Uploading Files')消息。但我在客户端没有收到任何错误或成功消息。我也没有在终端中看到收到了上述路由的POST请求。但是,在2分钟(每次)之后,终端记录为包括console.log()消息的路由接收的请求。这是我在客户端得到回复的时候。
  3. 终端记录:

    Uploading Files
    undefined
    POST /dashboard/template/upload 200 **120004ms**
    Uploading Files
    undefined
    

    这超出了我的范围。我不认为客户端会产生任何飞行前检查。如果有人能够提供有关问题的见解,那就太棒了。

1 个答案:

答案 0 :(得分:1)

来自Express 3的

req.files来自身体解析器中间件。在4.x中,这不再与Express一起打包。您可以安装multer并按照文档中的说明添加req.files

相关问题