I.K.
I.K.

Reputation: 464

Retrieve Absolute File Path With Javascript

Lets say you have a web application that uses NodeJS and ReactJS. Both are working on your local machine. NodeJS is accepting some files that are selected from ReactJS GUI with a simple file upload. Like this :

<input type="file" id="fileUploaderInput" ref="fileUploader"/>

You want to pass this file to your NodeJS so that it will perform some big data operations. However, since the Browsers does not have the access to client's File System, you can not take the absolute path of the file selected. Hence you can not inform your NodeJS server about the file. What should be the best approach for this?

I tried reading the file with react and then write it to a path where NodeJS already knows, but it does not seem to me as a best approach.

Upvotes: 0

Views: 1449

Answers (3)

Rahul Rana
Rahul Rana

Reputation: 455

It's quite simple. When you upload a file like

<input type="file" />

You get a file blob, you can send this blob to the server using rest API or parse data and then can pass this data to the server.

Upvotes: 0

jenil christo
jenil christo

Reputation: 684

It is not posible for a browser to get the absolute url of a file uploaded.This would be a security violation .

So you cannot send the absolute file path and read it via fs in node. You can either pass the base64 from client and handle file upload in Node.js or use desktop alternative like Electron.

If your app always runs in local you can also make the download folder predefined say for example (C:/Downloads)in Node.js and always upload files from the same folder, sending the filename from client.So if you select a file with name a.jpg,your Node.js code in local can use the fs to read from path C:/Downloads/a.jpg

Upvotes: 0

Peter Lehnhardt
Peter Lehnhardt

Reputation: 4995

If your app will always be sitting on your local machine, a desktop app via electron will be a valid approach (as idmean noticed). There you can use the nodejs module fs to work with files even in the frontend, which is enabled via inter-process-communication to the backend. If otherwise the nodejs-server will be sitting in the internet in the future, uploading the file and saving it via the nodejs-server is probably the best approach.

Upvotes: 1

Related Questions