I have a xmlhttprequest which uploads the file and I am trying to receive it in my node-express server. but for some reason I am not able to retrieve the file content in the server. Not sure where I am missing it.
app.post('/api/uploadfiles', function(req, res) {
console.log("apicalled");
console.log(req);
console.log(req.body);
console.log(req.files);
console.log(JSON.stringify(req.files));
});
In order for you to see the files, you will need to add another middleware that parses multi-part request.
Try using connect-multiparty module like so:
var multipart = require('connect-multiparty'); //for files upload
var multipartMiddleware = multipart();//for files upload
app.post('/api/uploadfiles', multipartMiddleware, function(req, res) {
console.log("apicalled");
console.log(req);
console.log(req.body);
console.log(req.files);
console.log(JSON.stringify(req.files));
});
Related
I have 2 nodeJS services and I would want to upload file in a dir, from one NodeJS (backend) to another NodeJS(backend). The receiver nodeJS is an express app.
Looking for some working code sample.
PS: Couldn't find any code samples in search, since everywhere it was Multer from client to server uploads that receives multipart/form-data.
Uploading file using POST request in Node.js
Receive the file first as you correctly said using Multer. Then, you may either save the file to a temporary directory before uploading it again or just send the file as-is.
You need to setup a server running with Multer on the 2nd server that wishes to receive the file.
const express = require('express');
const app = express();
const upload = multer({ dest: 'files/' });
app.post('/upload', upload.single('file'), (req, res) => {
res.sendStatus(200);
});
app.listen(3001);
Then on the server you wish to send the file from, do something like this:
const request = require('request');
const req = request.post('localhost:3001/upload', (err, res, body) => {
if (err) throw new Error(err);
if (res && res.statusCode == 200) {
console.log('Success');
} else {
console.log('Error');
};
});
const form = req.form();
form.append('file', fs.createReadStream('./location/to/file'));
I'm trying to store an uploaded file,the file reached the server successfully but don't know how to store it using the multiparty library that's the code:
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
app.post('/upload_audio', multipartMiddleware, function(req, resp) {
console.log(req.body, req.files);
if(req.files){
resp.status(200).send("Uploaded!!!");
}
});
By default the 'connect-multipart' module save the file in a default file which is
"C://Users//ur-username//AppData//Local//Temp" but you can change it by adding this line :
app.use(multipart({ uploadDir: "ur_path"}));
Problem
I have a server that needs to upload files, I have tried multiparty, connect-multiparty and multer.
But every case, has the same problem: the file only uploads some times, i mean, i could send a file and there is a chance that the libraries don't parse the files, and never continue the code, resulting on not uploading the files.
In a While, the request send an error "Request Aborted", but its the normal response when the request time out
This is the problematic node.js file:
var multiparty = require('multiparty');
var multer = require('multer');
var upload = multer({
dest: "/uploads/"
});
///----rest of code----
//1. Multiparty
app.post("/upload",[function(req, res){
var form = new multiparty.Form({uploadDir:'/uploads/'});
console.log("to upload")
form.parse(req, function (err, fields, files) {
console.log("uploaded");
res.json({uploaded: true});
})
}]
//2. multer
app.post("/upload2",[
function(req, res, next){
console.log("to upload");
next();
},
upload.fields([
{name: "file"},
{name: "thumbnail"}
]),
function(req, res){
console.log("uploaded");
res.json({uploaded: true});
}]
Make sure your form looks like this
<form enctype="multipart/form-data" action="..." method="...">
...
</form>
And to be honest you will be better off using node-formidable. It is the most used multipart/form-data package on npm.
The example works straight out of the box.
Cheers
https://stackoverflow.com/a/23975955/4920678
I was using the setup from this answer, to use http and https over the same Port.
Turns out, the setup with that proxy damaged the packages that where too large or something, and then the files never get parsed
I am developing a web app with node js. When trying to upload a picture and save in the file system of the app I get the error :
Cannot read property 'displayImage' of undefined
My code for the post of the image is the following:
router.post('/upload', function (req, res, next) {
fs.readFile( req.files.displayImage.path, function (err, data) {
var newPath = __dirname + "/uploads/uploadedFileName";
fs.rename(newPath, 'filename', function (err) {
res.redirect('/');
});
});
});
And in the view
form(action="upload", method="post", enctype="multipart/form-data")
input(type="file", name="displayImage")
input(type='submit')
Thanks a lot for your help!
PS: I also have read some tutorials in where formidable module is used. It is recommended to use it or as I have done is enough?
Which version of express are you using ? In express 4.0 for multipart bodies you should use an alternatives.
For example, you can implement upload files using multer npm module
var multer = require('multer');
app.use(multer({dest: './uploads/'}));
//app.post('/upload', function (req, res, next) {
// console.log(req.files);
//});
I am trying to upload files using express and formidable (eventualy forwarding to MongoDB and GridFS). I am starting by creating a form with a field of type file. On the action of that field I use the following route....
exports.addItem = function(req, res, next){
var form = new formidable.IncomingForm(),
files = [],
fields = [];
form
.on('file', function(field, file) {
console.log(field, file);
})
.on('end', function() {
console.log('-> upload done');
});
}
Everything runs fine but when I post I don't see anything in the console and it hangs.
The route looks like the following...
app.post('/item/add', routes.addItem, routes.getPlaylist, routes.index)
Any ideas?
UPDATE
Here is an example of grabbing the file, however, this still doesn't include formidable...
https://gist.github.com/2963261
The reason it is hanging is because you need to call next() to tell Express to continue.
Also use the bodyParser() middleware in express (included by default) to get the files. Something like this:
exports.addItem = function(req, res, next){
if(req.files.length > 0)
{
// process upload
console.log(req.files);
}
next();
}