How to upload multiple files in React-Redux - node.js

I had a query that I wanted to ask you about. I was building an application in React-Redux with Express NodeJS as backend, and postgreSQL as db. I wanted to implement a File Upload component into it. Can you please tell me how should I do that ?
Our team had previously implemented file upload in angular using multer on the backend. When we did the same in redux the small files get uploaded fine but when I try to upload a file over 4 mb it re-renders the page before the file is completely uploaded.
Please guide me how should I do this ? If you have a code sample that I can understand, that will also be great.

It is possible to upload multiple files at once in React.
<input type="file" multiple
name="myImage" accept=".png, .jpeg" className="multiple-upload"
onChange={this.uploadScreenshotFile} />
Here is uploadScreenshotFile function
uploadScreenshotFile(event){
for(let size=0; size < event.target.files.length; size++){
console.log('Selected file:', event.target.files[size]);
let file = event.target.files[size];
console.log("uploading screenshot file...");
// Do necessary request to upload here.......
}
}

Related

HTML file upload uploads missing icon instead of chosen image

So I am going to be making a very, very, very simple photo cloud storage using Firebase's Storage. Everything is going as planned except when I upload an image through HTML to send to the backend, it just sends something similar like this:
And that's the missing image icon! So here is my code for the file upload:
<!--HTML code, inside of a public folder-->
<form enctype="multipart/form-data" method="POST" action="/submit-form">
<input name="file" type="file" accept="image/png" />
<input type="submit" value="submit" />
</form>
//The code which sends the image to firebase's Storage
var bucket = admin.storage().bucket();
app.post('/submit-form', (req, res) => {
var imageChosen = `${req.body.file}`; //I know it's useless to add the `${}` but I just do it, ok!
fs.writeFile('sentImage.png', imageChosen, function (err) {
if (err) throw err;
console.log('Saved!');
});
bucket.upload('sentImage.png');
res.end('Image sent!')
});
So why is it only sending the missing image icon?
The point
If you don't want the detailed explanation, here is a summary below:
I am sending an image through an HTML form inside of a public folder, then it saves it to a local file and uploads it to Firebase's Storage, except that it's sending the missing image icon instead of the image uploaded through the HTML form.
How the cloud storage works
So basically you upload an image, then HTML sends the file to the backend. After that the backend uses the fs module to save it to a local file for Firebase to upload it to it's Storage

How to read a file in Node JS / Express JS Project?

In my Node JS / Express JS project, I need to get an excel project and I will be using this library read-excel-file.
I need to get the file path in order to continue with this code from the library documentation:
const readXlsxFile = require('read-excel-file/node');
// File path.
readXlsxFile('/path/to/file').then((rows) => {
// `rows` is an array of rows
// each row being an array of cells.
})
I don't understand about the file path, I can't get it from an <input type='file' /> I only get the file name.
but the location of the file is on the client device not on the server so how could this workout?
You CAN NOT access file on client file system from an HTTP server. You will need to send the file from client to server.
There's a lot of resource available online which can help with file upload but the gist is that file is send as a multipart-data from client to server. In Express server, multer module is used to access the file in req.file property.

how to read image stored in mongodb and display in nodejs

I am making a nodejs app which displays pictures stored on servers ,I was using multer to store pictures in the same directory and I was using mongodb as my database to store the path of the picture that user uploads , and then i read the path and displayed the pictures something like this,
<div class="post-image flex">
<%var imagesource='../'+postobj.blob.path%>
<div>
<img class='onbottomimage' src="<%=imagesource%>" >
</div>
</div>
everything was working fine locally.
but now I have deployed my app to heroku and found out I cannot store pictures on heroku as the user uploads them, I still have the pictures stored in mongodb in base 64 format something like this
image
:
Binary('/9j/4AAQSkZJRgABAgEAYABgAAD/7gAOQWRvYmUAZAAAAAAB/+EUI0V4aWYAAE1NACoAAAAIAAcBMgACAAAAFAAAAGIBOwACAAAA...', 0)
how do i convert them back to pictures and display them in img tag in ejs, or what other options do i have ,I dont want to change heroku but still be able to display the pictures that the user uploads.
If you are storing your uploaded images in the Heroku server, it is an utter waste. Because Heroku Dyno will restart every day which will delete all the extra added data other than data stored during deployment time.
I think you are using express.
let fs=require("fs")
let yourBuffer=//retrieve that buffer and store into this(yourBuffer) variable
let buffer = new Buffer.from(yourBuffer)
fs.writeFile(`location to storeimage/imagename.yourimageextension`, buffer, "binary", function (err, written) {
if (err) console.log(err);
else {
console.log("Successfully written");
res.sendFile((__dirname + `location of image/imagename.yourimageextension`))
}
});
I think a better solution would be using a 3rd party storage provider, aws s3 for example, and only store image url in the database

How to send an email from a form such as a contact form, with attachments

Im making a web app, using node.js, express.js and mongodb and trying get my contact form done. I would like site visitors to contact me via the form where they can put their name, email and message, along with an uploadable file image so they can show me what they want to be done as a sample through an image.
It seems like every websites have this functionailiry but I cant seem to find the answer Im looking for. Any help and guides would be appreciated.
i think you could use this library i've just found for uploading files with Javascript by using a file dialog: https://fineuploader.com/demos.
I think your issue is pretty much solved after that because for what concerns the form, you may easily create the input tags in HTML and then get data from them by using NodeJS.
To upload files you need to use a form-data handler. I use multer:
npm i multer
You upload a file like this:
const multer = require('multer')
const upload = multer({ dest: 'uploads' })
app.post('/profile', upload.single('image'), (req, res)) {
//Now the image is uploaded in uploads folder you just need to send it back
}
Note that image is a form's input name.
For infroamtion on how to send the image see this
Look also at the docs for multer
If you don't want to store image you can use then fs module to delete it.

Why use multer rather than manually upload your files from controller

So im new on using expressjs, usually i choose Laravel as my backend. but because some certain consideration, i choose expressjs.
On Laravel, when we handling file upload, we can write upload logic everywhere, its your freedom to do that. You can encapsulate it inside your model function, or put it on service, or anywhere you want.
But when i use expressjs, so many articles on internet that recommend us to use multer for upload your file. As my background is using Laravel previously, i found its weird to use multer. Its because multer is a middleware. Why on earth we use middleware to upload our images/files.
With this i cant encapsulate my business logic into one service and its make the code separated and with this thats mean i need to maintain one business logic from multiple place.
Could you explain me why everyone choose multer ?
why dont just upload it to our local storage manually ?( actually for now i dont know how to do this ).
What is pros on mins from using this library ?
multer is a body parsing middleware that handles content type multipart/form-data
That means it parses the raw http request data which are primarily used for file upload, and makes it more accessible (storing on disk / in memory /...) for further processing.
Without multer, you would have to parse the raw data yourself if you want to access the file.
With this i cant encapsulate my business logic into one service and
its make the code separated and with this thats mean i need to
maintain one business logic from multiple place. Could you explain me
why everyone choose multer ?
multer, just like other middlewares, can be used at the root for all routes, but can also be put on only specific routes too.
More on express middleware
First of all, Express/body-parser does not handle file uploads natively, so that is why you see other libraries being loaded to handle them. They are all going to be loaded as middleware so they can be injected into the request and handle that a file was actually uploaded.
Coming from a Symfony background, I understand where you are coming from with wanting to handle things more manually, as I do the same. There are other alternatives to multer; for example I use express-fileupload which allows you to load the the uploading middleware for your entire app, and then you can use req.files to handle your uploads. For example:
// load the file upload library as app middleware
const fileUpload = require('express-fileupload');
app.use(fileUpload({
limits: { fileSize: 50 * 1024 * 1024 },
}));
Then let's say you have a file input named 'foo':
<input name="foo" type="file" />
In your route you would handle it like so:
// now handle a file upload
app.post('/upload', function(req, res) {
console.log(req.files.foo); // the uploaded file object
});
The file-upload documentation has examples for the req.files object as well as options you can pass to the middleware itself.

Resources