Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

StackOverflow Point

StackOverflow Point Navigation

  • Web Stories
  • Badges
  • Tags
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Web Stories
  • Badges
  • Tags
Home/ Questions/Q 1622
Alex Hales
  • 0
Alex HalesTeacher
Asked: May 30, 20222022-05-30T21:48:46+00:00 2022-05-30T21:48:46+00:00

node.js – How to upload pdf files using nodejs and mongodb?

  • 0

[ad_1]

pls help me 🙁 i am trying to upload pdf files to mongodb using nodejs, express and pug; i tried as much as i can but nothing worked.

here’s my code:


connecting model database to mongodb

fileModel.js

const fileSchema = new mongoose.Schema({
file: {
    type: String,
    required: [true, 'Must have an uploaded file']
  }

used multer and will not use gridfs; i also have an update users profile within this app and its working; but this one doesn’t.

fileController.js

const multerStorage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'public/files');
  },
  filename: (req, file, cb) => {
    const ext = file.mimetype.split("https://stackoverflow.com/")[1];
    cb(null, `file-${file.fieldname}-${Date.now()}.${ext}`);
  }
});

const multerFilter = (req, file, cb) => {
  if (file.mimetype.split("https://stackoverflow.com/")[1] === 'pdf') {
    cb(null, true);
  } else {
    cb(new AppError('Not a PDF File!!', 400), false);
  }
};

const upload = multer({
  storage: multerStorage,
  fileFilter: multerFilter
});

exports.uploadFile = upload.single('file');

exports.createFile = async (req, res) => {
  const newFile = await File.create({
    file: req.file.filename
  });
};

upload-file.js

export const upload = async (data) => {
    try {
        const res = await axios({
            method: 'POST',
            enctype: 'multipart/form-data',
            url: 'http://127.0.0.1:3000/api/files',
            data
        });

        if (res.data.status === 'success') {
            showAlert('success', 'File uploaded successfully!');
            window.setTimeout(() => {
                location.assign('/documents');
            }, 1500);
        }
    } catch (err) {
        showAlert('error', err.response.data.message);
    }
};

index.js

const uploadForm = document.querySelector('.form--file');

if (uploadForm)
  uploadForm.addEventListener('submit', e => {
    e.preventDefault();
    const form = new FormData();
    form.append('file', document.getElementById('file').files[0]);
    upload(form, 'data');
  });

add-files.pug

.custom-file.mb-3
   label(for="file" class="form-label") 
   input#file(class="form-control form-control-lg", name="file", type="file")
button.button11.btn.btn-primary.btn-lg(type="submit", value="Submit") CONFIRM

THE ERROR

TypeError Cannot read properties of undefined (reading 'filename')
UNHANDLED REJECTION! Shutting down...

i also tried:

file: req.files.file

but the error that i got is:

ValidationError File validation failed: file: Cast to string failed for value "{
  name: 'the-filename.pdf',
  data: <Buffer 25 50 44 46 2d 31 2e 34 0a 25 f6 e4 fc df 0a 31 20 30 20 6f 62 6a 0a 3c 3c 0a 2f 54 79 70 65 20 2f 43 61 74 ... 24353172 more bytes>,
  size: 2435322,
  encoding: '7bit',
  tempFilePath: '',
  truncated: false,
  mimetype: 'application/pdf',
  md5: 'a2bb637f0d2b563e0eaf511fde0cd0',
  mv: [Function: mv]
}" (type Object) at path "file"
UNHANDLED REJECTION! Shutting down...

so what did i do wrong? :<

[ad_2]

  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report
Leave an answer

Leave an answer
Cancel reply

Browse

Sidebar

Ask A Question

Related Questions

  • xcode - Can you build dynamic libraries for iOS and ...

    • 0 Answers
  • bash - How to check if a process id (PID) ...

    • 4796 Answers
  • database - Oracle: Changing VARCHAR2 column to CLOB

    • 1063 Answers
  • What's the difference between HEAD, working tree and index, in ...

    • 1009 Answers
  • Amazon EC2 Free tier - how many instances can I ...

    • 0 Answers

Stats

  • Questions : 43k

Subscribe

Login

Forgot Password?

Footer

Follow

© 2022 Stackoverflow Point. All Rights Reserved.

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.