so I'm trying to upload an image with Multer but I want to use Angular's $http.post to upload the file. Not have a submit button trigger the form method and action. The problem is if I do not use encrypt, method or post attributes the req.file ends up being undefined and the image does not show up in the uploads folder.
So my question is, is there any way I can use Multer file upload not by the regular form method with action but angular's $http.post(). When I do it now the req.file is always undefined.
Here's my code for reference
app.js (Node)
var express = require('express');
var http = require('http');
var path = require('path');
var fs = require('fs');
var crypto = require('crypto');
var multer = require('multer');
var bodyParser = require('body-parser');
var app = express();
var port = process.env.port || 8080;
app.set('view engine', 'ejs');
app.use('/assets', express.static(__dirname + '/public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
var path = require('path');
var multer = require('multer');
var storage = multer.diskStorage({
destination: './public/uploads/',
filename: function (req, file, cb) {
crypto.pseudoRandomBytes(16, function (err, raw) {
if (err) { return cb(err); }
cb(null, raw.toString('hex') + path.extname(file.originalname));
});
}
});
var upload = multer({ storage: storage });
app.get('/', function (req, res) {
'use strict';
res.render('index', {filename: filename });
});
app.post('/', function (req, res) {
'use strict';
});
app.post('/upload', upload.single('image'), function (req, res) {
filename = req.files;
console.log(req.files);
});
app.listen(port);
HTML Form:
<form action="/upload" method="post" encrypt="multipart/form-data">
<div class="form-group">
<label for="image">Choose Image</label>
<input id="inputImage" name="image" type="file">
<button class="form-control" ng-click="uploadFile()">Add</button>
</form>
So I basically want to remove this default behaviour and still get the req.file object.
And finally my Angular code:
$scope.uploadFile = function(){
var file = $scope.myFile;
var uploadUrl = "/upload";
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl,fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
console.log("success!!");
})
.error(function(){
console.log("error!!");
});
};
Please help me on this... Right now I get the $http.post() .error() callback and if I dig deep into it, it is because req.file is undefined in my node app.js