NodeJS:处理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); }); 

现在的问题是,当我select一个文件,然后点击上传button,一个Ajax请求。 我logging了我发送的数据,在客户端似乎很好。 在服务器端有两个问题。

  1. (问题通过@Scimonster的答案解决)我没有看到req.files参数中的任何文件。 我以前在Express 3.x中没有任何问题。 现在我正在使用Express 4.x,也许我错过了一些东西。
  2. 第二个问题是,当请求被发送到服务器时,terminal立即loggingconsole.log('Uploading Files')消息。 但是我没有收到客户端的任何错误或成功消息。 我也没有看到在terminal收到一个POST请求提到的路线。 然而,2分钟后(每次),terminal都会logging收到的路由请求,包括console.log()消息。 这是当我在客户端得到回应。

terminallogging:

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

这超出了我。 我不认为有客户端产生任何飞行前检查。如果有人能够提供有关问题的可能性,这将是伟大的。

来自Express 3的req.files来自body parser中间件。 在4.x中,这不再与Express一起打包。 您可以安装multer并按照文档中的说明包含它,以启用req.files