I am trying to create a file loader with my own file file in JavaScript, and I want to upload files via XMLHttpRequest (without jQuery) to a Node.js server that uses Express.js.
The reading part of the file works fine, and when I download the file without XMLHttpRequest, it works fine (the files are in req.files in Express.js).
The problem is loading via AJAX: req.files is always empty.
Here is the code:
The form:
<form action="http://localhost:3000/upload" method="POST" enctype="multipart/form-data" name="form"> <input type="file" name="uploads" id="files" multiple="multiple"> <input type="submit" name="submit" value="submit"> </form>
The loadable part in the interface (in the files [0] .data is a file - not an array or something else):
function uploadFiles(files) { var xhr = new XMLHttpRequest(); xhr.submittedData = files;
The backend where the problem occurs:
exports.receiveUpload = function(req, res){ console.log(req.files);
And here are some Express.js configurations (I already had the same error without AJAX - in the comments in the code you can see the lines and the post that decided to download it without AJAX):
// all environments app.set('port', process.env.PORT || 3000); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.json()); app.use(express.urlencoded()); // this 3 lines have to be before app.use(app.router) // https://stackoverflow.com/questions/21877098/upload-file-using-express-failed-cannot-read-property-of-undefined app.use(express.multipart()); app.use(express.bodyParser({ keepExtensions: true, uploadDir: path.join(__dirname, 'public', 'uploads') })); app.use(express.methodOverride()); app.use(app.router); app.use(require('less-middleware')(path.join(__dirname, '/public'))); app.use(express.static(path.join(__dirname, 'public')));
Thanks in advance!
Hi,
FROM.
chrilehner
source share