DEV Community

Cover image for Build File Upload/Download Functionality with Image Preview using MERN stack

Build File Upload/Download Functionality with Image Preview using MERN stack

Yogesh Chavan on October 09, 2020

Introduction In this article, we will create a file upload and download functionality with a preview of the image using the MERN stack. ...
Collapse
 
akemylia profile image
Akemylia

Hi..i faces some problem here when i try run the npm

Image description

Collapse
 
myogeshchavan97 profile image
Yogesh Chavan

Looks like you have installed react-router-dom version 6. Please use version 5 of react router dom.

Collapse
 
akemylia profile image
Akemylia

I try to follow as you show and change it to yarn but it show like this.

Image description

Collapse
 
myogeshchavan97 profile image
Yogesh Chavan

You can clone the final code repository from here which is working fine or you can share your github repository so I can check what's causing the error

Thread Thread
 
Sloan, the sloth mascot
Comment deleted
 
akemylia profile image
Akemylia

Hi..I already change the react-router-dom to version 5 bit it still does not work. This my github repository..github.com/Akemylia/File-testing

Thread Thread
 
myogeshchavan97 profile image
Yogesh Chavan

You're missing bootstrap, react-bootstrap npm packages.
Install them using

npm install bootstrap react-bootstrap

OR

yarn add bootstrap react-bootstrap
Enter fullscreen mode Exit fullscreen mode

Also, you have named the file style.scss instead of styles.scss that's why you're getting error.

Thread Thread
 
akemylia profile image
Akemylia

already done it..but it seem another error popup..
Image description

Thread Thread
 
myogeshchavan97 profile image
Yogesh Chavan

You can clone the final repository code and use it.

Thread Thread
 
akemylia profile image
Akemylia • Edited

olrite sir..I will try to run the code first..I want to ask sir if it possible to use mongodb compass instead for this project? Also can it be run when we use npm instead of yarn?

Collapse
 
manish_1276 profile image
Manish Chaudhary

I needed to ask about, if i could delete the image file inside given source , how can I delete it and not display on the browser.

_ The given file is all deleted but still it shows its title and description.

Image description_

Collapse
 
myogeshchavan97 profile image
Yogesh Chavan • Edited

You can use fs.existsSync function to check, If the file exists or not inside the getAllFiles route and add only those files that exist, like this:

Router.get('/getAllFiles', async (req, res) => {
  try {
    const files = await File.find({});
    const finalFiles = [];
    files.forEach((file) => {
      if (fs.existsSync(file.file_path)) {
        finalFiles.push(file);
      }
    });
    const sortedByCreationDate = finalFiles.sort(
      (a, b) => b.createdAt - a.createdAt
    );
    res.send(sortedByCreationDate);
  } catch (error) {
    res.status(400).send('Error while getting list of files. Try again later.');
  }
});
Enter fullscreen mode Exit fullscreen mode
Collapse
 
manish_1276 profile image
Manish Chaudhary • Edited

got this err message, even if I submit some file the file will be uploaded but it won't show in the given display

Image description

*Can i ask you for a help if i can make this file preview before downloading too? *

Thread Thread
 
myogeshchavan97 profile image
Yogesh Chavan

Check your server console for errors you're getting, you will be able to find out what's going wrong.

Collapse
 
archana382 profile image
Archana Shrestha

hello, thank you for the explanation. I am getting error while uploading. Could you please help me solve this error.

Image description

Collapse
 
myogeshchavan97 profile image
Yogesh Chavan • Edited

Looks like you have not created a files folder in your server folder. Create one and try again.

Collapse
 
mahamadounouridine profile image
Mahamadou-Nouridine

thank you very much, nice explanation

Collapse
 
myogeshchavan97 profile image
Yogesh Chavan

Glad you found it useful. Thanks for reading @mahamadounouridine

Collapse
 
mahamadounouridine profile image
Mahamadou-Nouridine

It's been a pleasure @myogeshchavan97 🙏🏽

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
yeshangunaward1 profile image
Info Comment hidden by post author - thread only accessible via permalink
Gune

I did that as well. But it still gives that same error :(

Collapse
 
onidemon profile image
onidemon

Thank you for the tutorial! I have an issue though, the file list page will crash if refreshed and get a cannot get 404 error. Works fine when i refresh the main page but not the list page. Also the file list is giving an error about the favicon.

Refused to load the image because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'img-src' was not explicitly set, so 'default-src' is used as a fallback.

Collapse
 
myogeshchavan97 profile image
Yogesh Chavan

Thanks for pointing out the 404 error. You just need to add the following code inside the server/index.js file before the app.listen call

app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, '..', 'build', 'index.html'));
});
Enter fullscreen mode Exit fullscreen mode

I have updated the article with these instructions at the end of the article. So please check that out.

Regarding the favicon error, I'm not able to reproduce that. You might not have the favicon.ico file in the public directory so that might have caused that issue. But that is fine, Its not required for the application.

Collapse
 
webandmobiledeveloper95 profile image
Maxim Claynin

Thanks for giving the precious tutorial.
I just followed the full tutorial. Uploading is work, but donwloading has got an issue.
'downloadjs' successfully download the file, but can't open.
Text format files like .txt, .doc, are able to open, but media files like .png, .mp4 can't be open even though they're successfully downloaded.
Hope you give me resolution.

Collapse
 
myogeshchavan97 profile image
Yogesh Chavan • Edited

Hi @webandmobiledeveloper95 , the code works even for images and mp4. Please clone my final repository code and check If it works. You might have missed something to add.

Collapse
 
akemylia profile image
Akemylia

Sir can you teach me how to setup the mongodb using window..i try to follow the instruction in this article levelup.gitconnected.com/how-to-in... but I seem stuck with it.

Collapse
 
princezakabdull profile image
Engnr. Zaks

Thank you sir. This is a very important piece that we're learning from.
One thing though. How do we get to display the image along side the details. I want to upload to the server and then get to display them later. to test this, I added an extra td with img with src to the path from the API response

Collapse
 
princezakabdull profile image
Engnr. Zaks

but that hasn't been working

Collapse
 
olsard profile image
olsard

Cool, thanks for sharing!

Collapse
 
myogeshchavan97 profile image
Yogesh Chavan

Thank you 🙂

Collapse
 
priyank17 profile image
Priyank-17

Sir can show how to delete a particular file.

Collapse
 
myogeshchavan97 profile image
Yogesh Chavan

You can use unlinkSync function in Node.js to delete a file like this:

const fs = require('fs')

try {
  fs.unlinkSync("path_of_the_file_you_want_to_delete");
  // file removed -  return success
} catch(err) {
  console.log(err); // error while deleting file
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
atulyajaiswal profile image
AtulyaJaiswal

return download(response.data, "Resume", "application/pdf");

response.data is showing undefined and in response i have parameters like basic and url data parameter is not present there

Collapse
 
ndthanhdev profile image
Duy Thanh Nguyen

How to handle high dimension photo

Collapse
 
myogeshchavan97 profile image
Yogesh Chavan

This application will work for files with any dimension. You just need to change the fileSize property of the limits property in server/routes/file.js file, If the file you're uploading is larger in size. Currently, I have set it to only 1MB which I verified for 4291 × 3218 dimension which is this image

limits: {
    fileSize: 1000000 // max file size 1MB = 1000000 bytes
  }
Collapse
 
vinodonweb profile image
vinod sharma

download function not working can you please help me

Some comments have been hidden by the post's author - find out more