After looking at this article: http://lollyrock.com/articles/express4-file-upload/
I've realized that Multer used to allow file uploads when you did not know the name of the form field being uploaded. For example, if you look at the "using Multer" section of the article, you'll see that the writer does not use either .single()
, .array()
, or .fields()
when calling app.use()
. If you do that with the current version of Multer, you'll get the error TypeError: app.use() requires middleware functions
.
While I have a slight idea as of how to use .single()
, .array()
, or .fields()
, my current project requires that I send an unspecific amount of files to my server (may be a series of .png
or .log
files). Therefore, I don't know what the field names will be beforehand.
Doing that was easy with the version of Multer used in the article (0.1.6), but seems impossible when attempting it in the current version of Multer (1.0.3) since you need to specify the form fieldnames.
Alternatively, finding a full guide of Multer online has been a challenge, since the best one seems to be the Readme of the GitHub repo, and that one seems to be lacking. Maybe the answers that I'm looking for will be in a guide somewhere.
Thank you!
Just use multer.any() and you get those files in request.files.
var router = express.Router();
var app = express();
var _fs = require("fs");
var _config = require("./config");
var multer = require("multer");
var upload = multer({ dest: _config.tempDir })
app.use(bodyParser.urlencoded({extended:true}));
app.post("/api/files", upload.any(), function(req, res){
var files = req.files;
if(files){
files.forEach(function(file){
//Move file to the deployment folder.
var newPath = _utils.DetermineFileName(file.originalname, _config.destinationDir);
_fs.renameSync(file.path, path.join(_config.destinationDir, newPath));
var newFileName = path.basename(newPath);
console.log(newFileName + ' saved at ' + _config.destinationDir );
});
}
};