2

I am using Nodejs readStream.pipe(writeStream). How can I get the full path of the file I am uploading and assign it to createReadStream. I get only filename and When the file is in nodejs root directory it is fine no error but when I upload from anywhere else I get an error:

events.js:183
      throw er; // Unhandled 'error' event
      ^

Error: ENOENT: no such file or directory, open 'C:\Users\Esen\Documents\GitHub\gbmsturbo\nike.png'

I know that this happens because nike.png that I am uploading is not in "C:\Users\Esen\Documents\GitHub\gbmsturbo\". It is inside this folder: "C:\Users\Esen\Documents\GitHub\filestoupload"

I tried

function throwErrorDontCrash() {
   process.on('uncaughtException', function (err) {
      console.error(err.message)
   })
}

and this prevents nodejs crash and uploads the file but with empty content (0 byte)

router.post('/upload', (req, res) => {

    var filePath = req.body.file
    var ext = path.extname(filePath)
    var filename = path.basename(filePath, ext)

    var newVerFilePath = "public/uploads/" + newVerFileName+ext

    const readStream = fs.createReadStream(filePath)
    throwErrorDontCrash()
    const writeStream = fs.createWriteStream(newVerFilePath)
    readStream.pipe(writeStream)


function throwErrorDontCrash() {
  process.on('uncaughtException', function (err) {
    //console.error(err.message)
  })
}

and here is my form file

<form class="center" action="/upload" method="post">
<input id="file" type="file" name="file" required encrypt="multipart/form-data"/>
<input type="submit" value="UPLOAD">

I want filePath to include the directory path where ever the file is uploaded when user clicks on Choose or Browse button. Currently, filePath gets only filename such as nike.png and my expectation is to get "C:/Users/Esen/Documents/GitHub/filestoupload/nike.png"

Elliot Nelson
  • 11,371
  • 3
  • 30
  • 44
Ethan Rock
  • 21
  • 1
  • 2

1 Answers1

0

it looks like you are writing an express app on nodejs. Your issue is here:

const readStream = fs.createReadStream(filePath);

I think that you believe this is how you "read" the file the user is uploading, but that's actually not possible - the "fs" module doesn't exist in the browser. The user navigating your website is uploading the image from their computer via a form, which means the image is coming in from the HTTP request (the req object), not from the file system.

(This can be confusing because in your case, you probably are running this express app locally on your machine, but it's easier to imagine it in production - the express app runs on a big server somewhere, and is a different computer than your user's computer, where the file being uploaded lives.)

Check out the related S.O. question How to upload, display and save images using node.js and express. Also, see the tutorial Upload Files or Images to Server using Nodejs.

Elliot Nelson
  • 11,371
  • 3
  • 30
  • 44