Uploading a file to nodeJS server - javascript

Client code:
var data = new FormData();
data.append(fileName, blob, 'test.html');
fetch('http://localhost:3000/', {
method: 'POST',
headers: {
},
body: data
}).then(
response => {
console.log(response)
}
).then(
success => {
console.log(success)
}
).catch(
error => {
console.log(error)
}
);
Server code:
router.post('/', urlencodedParser, function(req, res, next) {
const body = req.body;
console.log(body);
res.send(`You sent: ${body} to Express`);
});
I am sending a blob in the body of a post request. When I send it to the server I want the server to download the file from the body of the request. How can i download this file? Or is there a simpler way to upload from client?

If you can utilize an NPM package formidable, there appears to be a solution at: https://www.w3schools.com/nodejs/nodejs_uploadfiles.asp
Once you have the file received, you can use the fs module to save and store in server

May it can solve your problem.
const fs = require('fs');
let directory = '/temp/data'; // where you want to save data file
router.post('/', urlencodedParser, function(req, res, next) {
const body = req.body;
console.log(body);
fs.writeFile(directory, body, function(err) {
if(err) {
return console.log(err);
}
console.log("File has been saved");
});
res.send(`You sent: ${body} to Express`);
});

This solved my answer - https://attacomsian.com/blog/uploading-files-nodejs-express, which basically uses a middleware to do the upload.
This was basically like:
const x = 6;
console.log(x);
Error: value is f'd up
const x = 6;
magic.valueParse(x);
console.log(x);
6
Also, i would like to point out how bodyParser cannot be used for multipart data. It is mentioned on the official docs, but even responses I get seem to point to bodyParser. So I thought I'd re-iterate that.

Related

Undefined body of a fetch request (arraybuffer body) in node server

I've read a lot of similar questions, but any answer worked for me.
I'm trying to send an audio in the body of a fetch request (in vuejs) as an ArrayBuffer, but when I print it in the server side, the body is undefined.
Client code:
export async function makeQuery(data) {
let bufferAudio = await data.arrayBuffer();
console.log(bufferAudio);
const response = await fetch(`/api/query`, {
method: 'POST',
//headers: {'Content-Type': 'audio/mp3'},
body: bufferAudio,
})
.catch(function(e) {
console.log("error", e);
});
return response;
}
Node Server code:
const express = require('express');
const path = require('path');
const app = express(), port = 3080;
app.post('/api/query', async (req, res) => {
query = req.body;
console.log('query ', query); // Here the body is undefined
/*
Do some processing...
*/
});
When I send a simple json string in the request body (and app.use(express.json()) in the server)it works. But not with the arraybuffer audio. Thanks in advance

Get File from POST request body NodeJS & Angular

I am working on an MEAN Stack application and I am trying to manage a form that allows users to upload a file when they submit. It appears to be working on the client side, however when I send the post request from the client and inspect the request body the file is an empty object. It is just a small .docx file so it should be fine size-wise. But I do not understand why nothing is properly received since the request goes through with out error. I was under the impression that files could be sent this way.
Am I missing something?
code from angular service
sendApplcation(data : any): Observable <any>
{
return this.http.post(this.url+ '/careers/api/application', data);
}
nodejs code
router.post("/api/application", (req, res) => {
const application = req.body;
console.log(req.body.file);
let email = {
to: `${req.body.email}`,
from: "Careers#TrueLogistics.ca",
subject: "Application Recieved",
text: JSON.stringify(req.body),
html: `<p> ${JSON.stringify(req.body)} </p>`,
};
mailer.sendMail(email, (err, res) => {
if (err) {
console.log(err);
}
});
email.to = "mjayfalconi#gmail.com";
mailer.sendMail(email, (err, res) => {
if (err) {
console.log(err);
}
});
res.json("Applcation Submitted Successfully!");
});
Check out the multer package on npm.
File upload works a bit differently than the normal request.
You will also set enctype to multipart at the front end.
Furthermore, I see you are using nodemailer to send the file as an attachement. Read the documentation about the attachment. You don't send the file that way.
//Dependencies
const multer = require('multer');
//Multer DiskStorage Config
const diskStorage = multer.diskStorage(
{ destination: 'assets/profile_upload'} );
//Create Multer Instance
const upload = multer({ storage: diskStorage });
//File upload
//or app.post()
router.post('/upload-file', upload.single('file'), (req, res) => {
//The file
console.log(req.file)
;});
//Your code:
app.post('/upload', (req, res) => { ... try doing app.post('/upload' ,upload.single('file'),
Also check out this post: https://stackoverflow.com/a/61341352/9662626
Sorry for the bad formatting. I only have access to my phone at the moment.

How to write a zip file from a request body to a file on Node server?

I am trying to write a node server that can receive a zip file of PDFs and JSON. In order to utilize it on the server I need to write it to a file on the server where I can call other functions on the internal data.
However with my current method, I can successfully write to a file in the server but when trying to open it in windows, I get an error "The Compressed (zipped) Folder is invalid."
I've tried directly piping the request to fs.createWriteStream with the same result as the code below
app.route('/myRoute').post(rawParser, function (req, res, next) {
let serverFileName = `${req.connection.remoteAddress.substring(7)}_${Date.now()}.zip`
let writeStream = fs.createWriteStream(`${__dirname}/${serverFileName}`, 'binary');
// console.log(req.rawBody);
writeStream.write(req.rawBody);
writeStream.end();
writeStream.on('error', err => {
logger.logger(err);
res.status = 500;
res.send("Server did not accept File");
});
writeStream.on('finish', () => {
logger.logger(`Writing to file: ${serverFileName}`);
res.status = 201;
res.send("Successfully Wrote file to server");
});
});
Here is my rawParser middleware
const rawParser = function (req, res, next) {
req.rawBody = [];
req.on('data', function (chunk) {
req.rawBody.push(chunk);
console.log(chunk)
});
req.on('end', function () {
req.rawBody = Buffer.concat(req.rawBody);
next();
});
}
I'm fairly new to node and javascript coding. I am welcome to any tips including your solutions

Unable to parse info from webpage

I am trying to parse info from this link on my node.js project
https://stockx.com/api/products/nike-daybreak-undercover-black?includes=market
Im able to get info when I access the link through postman and going on the url on a web browser. However when I try accessing the request through my node.js project, it is saying access is denied. Any idea why?
Thanks.
Here is my code:
const express = require('express');
const request = require('request');
const cheerio = require('cheerio');
const axios = require('axios')
const app = express();
app.get('/', function(req, res){
let shoe =req.query.shoe;
let url = 'https://stockx.com/api/products/nike-daybreak-undercover-black?includes=market'
request(url, function(error, response, html) {
if (!error) {
var $ = cheerio.load(html);
console.log(html)
res.send();
}
});
});
app.listen('8080');
console.log('API is running on http://localhost:8080');
module.exports = app;
You just need to add "User-Agent" in the header. The website from which you are trying to get the data is denying all requests without User-Agent to avoid scrapers.
const options = {
url: 'https://stockx.com/api/products/nike-daybreak-undercover-black?includes=market',
headers: {
'User-Agent': 'request'
}
};
request(options, function(error, response, html) {
console.log('err: ', error);
if (!error) {
var $ = cheerio.load(html);
console.log(html)
res.send(html);
}
});
I have tried the following code and it works
// ...
app.get('/', function(req, res){
// let shoe =req.query.shoe;
let url = 'https://stockx.com/api/products/nike-daybreak-undercover-black?includes=market'
axios({
method : 'get',
url,
headers : { withCredentials: true, 'User-Agent' : 'Postman' }
})
.then(data => {
console.log('data', data.data);
})
.catch(err => {
console.log('err', err);
})
res.send().status(200);
});

FormData server side NodeJS

I'm developing a web application using nodejs server-side. I'm trying to send pdf files from client to server.
Client:
var files = new FormData();
var count = 0;
$('#tableSlideId tr').each(function() {
var inputForm = $(this).find("th:first").children();
file = inputForm[0].files[0];
files.append((count++).toString(),file);
});
$.ajax({
type: "POST",
url: "/sendFiles",
data: files,
contentType: false,
processData: false,
}).done(function(err){
var text ="";
if(err) {
text = "Upload FAILED! Retry ...";
} else {
text = "Upload SUCCES!";
}
alert(text);
});
I think the client side is ok, infact if I use this loop:
for(var p of files)
console.log(p);
I correctly visualize all the elements that I want to send to the server.
Server:
app.post('/sendFiles', function(req,res) {
console.log("--->",req.body);
res.end();
});
Now in the server I have no idea how to visualize the data that I send, infact req.body is empty.
I don't know if this is the right way but my goal is to load some pdf files form the client, send to the server and after store them in a mySql dmbs.
Thank you.
Use express-formidable module. install 'express-formidable' by the running command
npm install express-formidable --save
a simple example is as follows from github
const express = require('express');
const formidable = require('express-formidable');
var app = express();
app.use(formidable());
app.post('/upload', (req, res) => {
//req.fields contains non-file fields
//req.files contains files
console.log(req.fields);
console.log(req.files);
});
Hope this helps!
Edit, from here -
app.post('/submit-form', (req, res) => {
new formidable.IncomingForm().parse(req, (err, fields, files) => {
if (err) {
console.error('Error', err)
throw err
}
console.log('Fields', fields)
console.log('Files', files)
files.map(file => {
console.log(file)
})
})
})
I think you need some middleware to accept the multipart formdata in the server side. Multer is a good option.
You can use
var multer = require('multer')
var upload = multer({ dest: 'uploads/' })
and then update your server side to handle the upload:
app.post('/sendFiles', upload.array('files', maxCount), function(req,res)

Categories

Resources