2016-02-10 132 views
0

我想上傳一個文件使用多功能,並且沒有請求正文或文件。有沒有人有任何想法我做錯了?Express Multer文件上傳請求身份和請求文件undefined

這是HTML

<form action="/upload" method="post" enctype="multipart/form-data"> 
    <input type="file" name="file-uploader"/> 
    <input type="submit"/> 
</form> 

這是我的js

const express = require('express'); 
const app = express(); 
const multer = require('multer'); 
const upload = multer({ dest: 'uploads/' }); 
// other stuff 
app.post('/upload', upload.single('file-uploader'), (req, res, next) => { 
    console.log(req.file); 
    console.log(req.body); 
    res.send ({'asdf': 'sadf'}); 
}); 
+0

而且您還包括Express? – adeneo

+0

是的我有,我會編輯的問題,包括它 –

+0

什麼版本的nodejs? –

回答

1

在快遞4,req.files不再默認REQ對象上可用。 這裏是我的解決方案具有強大:

前端: 標記:

<input type="file" id="file"/> 
<button id="send-file">Send</button> 

JS:

//send file 
var send_file = $("#send-file"); 
send_file.on("click", function(e) { 
    //file 
    var file = $("#file")[0].files[0]; 
    //formdata 
    var fd = new FormData(); 
    fd.append("file", file, "file_name"); 
    //send file 
    $.ajax({ 
      url: '/upload', 
      data: fd, 
      cache: false, 
      contentType: false, 
      processData: false, 
      type: 'POST' 
     }) 
     .done(function(data) { 
      console.log(data); 
      console.log("Upload successfully"); 
     }); 
}); 
return false;}); 

後端:

安裝強大:npm install formidable --save

而且最後一個p:

var express = require('express'); 
var app = express(); 
var path = require('path'); 
var fs = require('fs'); 
var formidable = require('formidable'); 


    app.post('/upload', function(req, res) { 


    // 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() { 
     console.log(Date.now()) 
     res.end('success'); 
    }); 

    // parse the incoming request containing the form data 
    form.parse(req); 

});