NodeJs how to store an uploaded file using multiparty - node.js

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"}));

Related

How to upload file from nodeJS to nodeJS

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'));

Setting correct headers for uploading file using Angular and Node

I'm having a headache trying to upload files to a Node server from an Angular 6 app. I have the following route handler in the Node app:
var express = require('express');
var router = express.Router();
// Route for /fileupload
//****************************************************************
// Multer module for uploading files
var multer = require('multer');
// set the directory for the uploads to the uploaded to
var DIR = './uploads/';
var upload = multer({ dest: DIR }).single('cloudImg');
router.post('/', (req, res, next) => {
var path = '';
upload(req, res, function(err) {
console.log('REQ HEADER', req.headers);
if (err) {
// An error occurred when uploading
console.log(err);
return res.status(422).send("an Error occured")
}
// No error occured.
path = req.file.path;
return res.send("Upload Completed for " + path);
});
});
module.exports = router;
I use the multer module for uploading the file. If I call the API from Postman, everything works fine:
But if I send the file from the Angular app, the Node server crashes giving this error: TypeError: Cannot read property 'path' of undefined.
I've realised that Postman sets this content-type header:
'content-type': 'multipart/form-data; boundary=--------------------------719034023986440712074389'
I'm pretty sure that the error happens because the Node server is expecting another type of data and it can't create the req.file object. I know how to set the content-type header, but how could I generate the boundary field? Or, is there any way to tell Angular httpClient methods to autogenerate the header for this case?
Thanks,

Method to parse req with multipart content type in node.js

Is there a way to extract file from http req without saving it on server ?
as there are some parser like Multer and Multiply , but they save file on server location first.
Can we parse file in node.js as we do in c# .Net
Request.Files
Resolved by using Multer in memory storage mode.
Like:-
var storage = multer.memoryStorage();
var upload = multer({ storage: storage });
this will keep file in buffer
and you can extract file like this
app.post('/upload', upload.any(), function(req, res) {
console.log(req.files);
});

receiving file in node-express uploaded with xhr

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));
});

Node Js Retrieve and display image

I am able to upload images using Node.Js and Multer. The images are saving in encrypted format with random names. How can I retrieve and display images in a .jade file or .hetml file?
//My Code to upload image
router.post("/upload", function(req, res, next){
if (req.files) {
console.log(util.inspect(req.files));
if (req.files.myFile.size === 0) {
return next(new Error("Hey, first would you select a file?"));
}
fs.exists(req.files.myFile.path, function(exists) {
if(exists) {
res.end("Got your file!");
} else {
res.end("Well, there is no magic for those who don’t believe in it!");
}
});
}
});
// Upload page (Jade file)
form#fileUpload(method="post" action="/uploads/upload" enctype="multipart/form-data")
label(for="payload") Select a file to upload:
input#fileToUpload(type='file', name='myFile')
//input#payload(type="file" name="myFile" accept="image/*")
br
button#upload Upload
var multer = require('multer'),
upload = multer({dest: 'uploads/'});
app.post('/multipart-upload', upload.single('file'), function(req, res){
var filename = req.file.path;
console.log('Uploading File: ' + JSON.stringify(req.file));
});
Multer needs a path to upload the file. You can keep the path inside the public/static folder of express, and directly link the file.
Or You can use the static files middleware to serve the files in the upload folder and directly link them.
app.use('/image-uploads', express.static('uploads'));

Resources