Simple file upload with Node.js - node.js

I am building a node.js application that uses pdf.js to read pdf files, but much like other js, pdf.js does not allow cross origin requests. So, I need a way to save files selected with a file input to my pdf directory. I'm not so great with node so make it as simple as possible if you can.

Here is a basic idea of what you need:
1st, require and use module 'connect-multiparty'. This will expose the req.files object in node.
var multipart = require('connect-multiparty');
app.use(multiparty({});
Then, in your controller method, require the 'fs' module, and use it to save the uploaded file.
var fs = require('fs');
fs.writeFileSync("myFileName", req.files.file.ws.path, function(err) {
if(err) { console.log(err); }
else { console.log("file uploaded"); }
});
Being familiar with node will help, but the two basic libraries you need to perform this are the aforementioned https://www.npmjs.com/package/connect-multiparty and http://nodejs.org/api/fs.html
edit: see the link in the comments below. this answer is incomplete and is better explained in the link

Related

How could I save an img in my express server that I receive from my client?

I have a client in React that sends a form data with a file. When that file arrives to the server, the body is parsed by body parser and its result is a buffer. The idea is that the file keep saved in some place of my server, because I want to use it later from my client. So I'd like to know how should I handle this problem.
I tried to write directly this buffer as a file with fs, but the file created has an error of format, so I can't access it.
You can do stuff like this
var fs = require('fs');
fs.writeFile('newImage', req.files.image, function (err) {
if (err) throw err;
console.log("It's saved");
});
correct parameter order of fs.writeFile is the filename first then the content.
If you're using express.bodyParser() you'll have the uploaded files in the req.files field.
And of course you should write the callback:
POV: Your image file should be in req.files not the body.
I think you need a package for storing a file on your backend service. I had used morgan package for that and I was satisfied with using it. I have just searched other packages for storing a file, i found express-fileupload package. Maybe you want to look at how to use those. If you want to store a file, using the third package would be better for you and for your effort.

file preview without downloading it using express

I'm trying to develop a file management web app and I want to add an option to preview files before downloading it I'm using Node Js express, is there any way to implement that.
or just a small guide because I tried all the possible solutions on the net but it's not working
Yes you can preview it, you just need to add declaration for your file path and you can access directly from url
const app = express();
const __dirname = path.resolve()
//public is the name of folder where your file is being stored
app.use("preview",express.static(path.join(__dirname,"public")));
So you can directly access the file using url expressurl/preview/filename and preview it wherever you want
You can use the built in node filesystem module fs to read and write to files on the server. So in your case you want to read the content of files, so something like this:
var fs = require('fs');
fs.readFile('my-file.txt', 'utf8', function(err, data) {
if (err) throw err;
console.log(data);
});

How to fetch mutiple images from express api's into react application?

I am using mern stack to program an application. I used multer package with express for file uploading and uploaded images in a directory in node.js application. Now i want to fetch the image from that directory. How can i do this? I have found
res.sendFile()
but there are cases when i will need to fetch multiple files from server at once. I also have found just sending path from api to react and serving from a folder into react which i don't find secure? how do i go about it?
You should decouple the back end from the front end, which means, separate the express part from the React part and make simple API, express also can serve files as static(search google for static file serving), then call the API from your React App. Just give the React App Image URL like example.com/static/image1.png(<img src={"example.com/static/image1.png"} />)
I ended up using streams for my problem the following snippet might come in handy for some one with similar issue.
const fs = require('fs')
const stream = require('stream')
app.get('path',(req, res) => {
const r = fs.createReadStream('path to file') // or any other way to get a readable stream
const ps = new stream.PassThrough() // <---- this makes a trick with stream error handling
stream.pipeline(
r,
ps, // <---- this makes a trick with stream error handling
(err) => {
if (err) {
console.log(err) // No such file or any other kind of error
return res.sendStatus(400);
}
})
ps.pipe(res) // <---- this makes a trick with stream error handling
});

Downloaded Ziggeo videos corrupt?

I'm on Windows 8.1 running node 10.22, express 4.11.2
I'm trying download a file from the Ziggeo API, but the resulting file comes out corrupt.
var express = require('express');
var app = express();
app.get('/download/:id',function(req,res){
downloadVideo(req.params.id,res);
});
function downloadVideo(id,res){
sdk.Videos.download_video(id,function(back){
fs.writeFile('downloadedVideo.mp4',back,function(err){
if(err){
console.log(err);
res.sendStatus(400);
}else{
res.sendStatus(200);
res.end();
}
});
});
}
The resulting file is corrupt and cannot be played.
When I download the same video using the Ziggeo dashboard, the filesize is bigger and I can play it back fine.
If I open the two files as text files and diff them, there are a few lines of similarities, but the files are largely different.
I've tried all three encoding types that writeFile takes as a parameter, but none of those help.
I also tried the Streams.download_video method, and that gives the same results.
Please try the updated SDK on GitHub:
https://github.com/Ziggeo/ZiggeoNodeSdk
Check the data that sdk.Videos.download_video passes to your callback. I expect that you are recieving JSON data (or some other data type), but are expecting a H.264 video. The Ziggeo API documentation states:
Whenever you interact with Server SDK, the Client API or Webhooks, you will receive resource objects from our system.
Try running file on your output video to identify what filetype you end up with
See The Ziggeo docs

Nodejs - writing and saving files

I am investigating how to download files to a user's local machine but I'm not quite sure what I need in order to do this. I'm using Nodejs and Express with Angularjs on the front-end.
User's can write text into a textarea and it's this text that will be written to the file.
To do this I have:
...
fs = require('fs');
fs.writeFile('filename.txt', textarea.text, function (err) {
if (err) return console.log(err);
res.send(200);
});
...
Once the file is created how do I get it to download on the user's machinea?
Use res.download
res.download('filename.txt');
http://expressjs.com/4x/api.html#res.download
If you don't need to store the file on the server, you could just sent it back to the user directly:
res.attachment('filename.txt');
res.set('Content-Type', 'text/plain');
res.send(textarea.text);
This is not only simpler but also improves performance (no disk i/o) and more secure (no untrusted files on your server).

Resources