Saving An Image file to Assets folder in React App - node.js

I am trying to upload a image in my react app and save it in my assets folder.
I have the DataUrl for the image , but when i am trying to write the dataurl to an image file using fs.writefile(), i am getting below error
var normalizeFilePath = (path: string) => (path.startsWith('file://') ? path.slice(7) : path);
|
| type MkdirOptions = {
ModuleParseError: Module parse failed: Unexpected token (30:29)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See ht tps://webpack.js.org/concepts#loaders
| };
my application is a gatsby -react Application.
on clicking the submit button , submit handler is called to write the data to file.
const submitHandler = (event) => {
console.log(event.target);
console.log(files.target);
fs.writeFile(`../assets/images/testimonialImage/${files.target.files[0].name}.png`, files.target.files[0], function (err) {
if (err) throw err;
console.log('Replaced!');
});
}
Tried using saveAs function but its downloading file to downloads folder.
What i need is , when i upload the file in frontend , it should save it in the assets/image folder.
As i am not having any backend for my app.

Your approach of uploading a file in frontend and saving it to assets/image is only going to work in a development environment. If you want it to work in production environment too, you NEED a backend. It could be a simple node.js server which saves the file to a folder.

Related

How to use node:fs inside of a vue app to save images into source directory

I'm building a personal portfolio website using Vue.js, and I'm attempting to build a form to allow me to add to my portfolio later. I'm storing the text data in firebase, but I also want to be able to upload and access pictures. I'm attempting to upload through a form and save with node:fs with the following
import { writeFile } from 'node:fs'
export function saveImages (data:FileList, toDoc: string) {
const reader = new FileReader()
const imageNames = []
console.log(toDoc)
for (let i = 0; i < data.length; i++) {
imageNames.push(toDoc + '/' + data[i].name)
reader.readAsBinaryString(data[i])
reader.onloadend = function (e) {
if (e.target?.readyState === FileReader.DONE) {
const imageFile = e.target.result as string
if (imageFile) {
writeFile('./assets/' + data[i].name, imageFile, 'binary', (err) =>
console.log('was unable to save file ' + data[i].name + ' => ' + err)
)
}
}
}
}
return imageNames
}
When I attempt to call saveImages, I get the error
ERROR in node:fs
Module build failed: UnhandledSchemeError: Reading from "node:fs" is not handled by plugins (Unhandled scheme).
Webpack supports "data:" and "file:" URIs by default.
You may need an additional plugin to handle "node:" URIs.
As pointed out by the comments on your answer, the Node.js-fs-module is cannot be used in the frontend. Here is why:
While developing your vue.js-app, you should remember that you always have to run a development server in order for the app to compile to a browser-readable format. The resulting page will not be delivered as some .vue-files and .js-files but everything will be bundled into an html-file and some additional .js-files.
While running the development server, the source directory of your app is 'lying' on a server, but this is not even the directory that is delivered to the browser.
In a production server, there will be static assets built out for your vue.js-app, which does also only contain .html- and .js-files.
When a client (browser) accesses a route, some static files will be delivered to the browser, and all the code you are writing in your .vue-files will be run on the client's machine, not on a server. So you cannot interact with server-side directories.
Therefore, you should look into a backend server framework, which you can connect to your frontend to allow users to upload files to a server, and those files would be saved on the server. You will then set up your vue app to communicate with the backend. Here are some additional resources:
Node modules with vue: StackOverflow
Express.js: popular backend framework for Node.js
Express.js: Deliver files
Blog article on Express.js file upload (Attacomsian)
You might also want to take a look on how to send static files with express, because once the files are uploaded and the server receives them, it could store them into a static-directory, where you could access them without having to use separate API-routes.

Files stored to public folder get reset node js

In my node js application I am turning user data entered through a form into a js object and then storing that js object as a json file in the public folder of my ejs server. This works all well locally on my computer however when I use Heroku all the files that get stored into the server from form requests reset after a while.
Below is what I'm going to store json files
fs.writeFile(
__dirname + "/public/" + "AddonPosts/" + addonFromFile.name + ".json",
JSON.stringify(addonFromFile),
function (err) {
if (err) throw err;
}
);
Is there any way to write to my server without it constantly resetting? Additionally would there be an easy way to then download that folder I have written to?
Thanks
heroku Free tier does not save the files that are uploaded/Newly Created when your app is running. It resets your app to the stage how it was uploaded.
In short, dynamic uploads/Saving are not possible.
Alternative way: Use mongodb atalas[Free 500mb] to store your data

How to fetch mutiple images from express api's into react application?

I am using mern stack to program an application. I used multer package with express for file uploading and uploaded images in a directory in node.js application. Now i want to fetch the image from that directory. How can i do this? I have found
res.sendFile()
but there are cases when i will need to fetch multiple files from server at once. I also have found just sending path from api to react and serving from a folder into react which i don't find secure? how do i go about it?
You should decouple the back end from the front end, which means, separate the express part from the React part and make simple API, express also can serve files as static(search google for static file serving), then call the API from your React App. Just give the React App Image URL like example.com/static/image1.png(<img src={"example.com/static/image1.png"} />)
I ended up using streams for my problem the following snippet might come in handy for some one with similar issue.
const fs = require('fs')
const stream = require('stream')
app.get('path',(req, res) => {
const r = fs.createReadStream('path to file') // or any other way to get a readable stream
const ps = new stream.PassThrough() // <---- this makes a trick with stream error handling
stream.pipeline(
r,
ps, // <---- this makes a trick with stream error handling
(err) => {
if (err) {
console.log(err) // No such file or any other kind of error
return res.sendStatus(400);
}
})
ps.pipe(res) // <---- this makes a trick with stream error handling
});

how to read the attachments stored using multer - nodejs/expressjs

I am new to node programming, I am trying to build an app which will be having a feature where users will be uploading there docs/images and then afterwards they can also view the same files which they had uploaded earlier.
I came across multer with which I built an API which stores the attached file on the server, please refer below code :
app.post('/submit-form', uploadPlugin.single('files'),(req, res) => {
console.log(req.file);
if (!req.file){
res.status(400).json({"error":"Something went wrong while uploading file"})
return;
}
else
{
path = "C:\\Users\\APIs" + req.file.path
console.log(path)
res.sendFile(path);
}
})
Now my problem is if at all I need to view the attached files, how can I do so (For ex: if someone uploads an Image it should show this image was uploaded)
I am trying to send the file as the response but in the HTML page it just shows gibberish (probably the byte stream, refer the image attached) instead it should display the actual document say image for example.

How to upload files to Cloud Storage from App Engine Application Create using Nodejs On Back End?

I have created an App in Nodejs, this App involves users to upload some files such as profile pictures and some other media file, so these files are stored in certain folders here in my Web Application folder.
This works well locally now after deploying my App when the user do an upload these picture and other files it return an error, I suppose I should be maybe doing some configuration on Cloud Storage and let my App Engine Application be able to read and write to such folder using NodeJs. Please help me with how I can achieve this.
I use this following Code to create these files from Base64 data which is Uploaded using Rest API
var data = req.body.image; //base64 image data
const bucket = storage.bucket(process.env.GCLOUD_STORAGE_BUCKET); //decalre bucket
var blob = bucket.file('new_image.png');
writeScreenShot(blob, data);
blobStream.on('finish', () => {
res.send("Success");
});
blobStream.end(req.file.buffer);
function writeScreenShot(blob, data)
{
var strm = blob.createWriteStream();
strm.write(new Buffer(data, 'base64'));
strm.end();
}
This is how I implemented it so far, but it returns image that says it looks like we don't support this image type while file extension of this image is png, it seems like I have created this image wrongly now got affected the metadata of it. Thanks in advance

Resources