How to store image from url to server folder using node js? - node.js

I am new to NodeJS and try to practice file upload from URL like this:
I have One url on which one image is placed. I want to upload that image into my server without download it anywhere. How can I do that ?
I tried node-fetch package to fetch buffer of image from URL and then try to write in my server using createWriteStream But failed.
Please help me. I don't know what is the correct way to upload file.
What I have tried :
import { createWriteStream } from 'fs';
import { pipeline } from 'stream';
import { promisify } from 'util'
import fetch from 'node-fetch';
const streamPipeline = promisify(pipeline);
const response = await fetch('http://dummy.com/5.png');
if (!response.ok) throw new Error(`unexpected response ${response.statusText}`);
await streamPipeline(response.body, createWriteStream('./img.png'));

Related

Create a Blob for Video in NodeJs18 and Use it on Client Side

Learning NodeJs and Blob, and I Try to Create a Blob from a Video File in NodeJS. And send this in a Json file to my Client. Data will be Fetch inside GetStaticProps in NextJS.
Here is What I Created in NodeJS Server :
const fileBuffer = fs.readFileSync(filePath); // Path is something like example.com/video.mp4
const blob = new Blob([fileBuffer], { type: 'video/mp4' });
blobUrl = URL.createObjectURL(blob); // Return blob:nodedata:c3b1baf2-fba8-404f-8d3c-a1184a3a6db2
It retrun this :
blob:nodedata:c3b1baf2-fba8-404f-8d3c-a1184a3a6db2
But How can I use it in Client ? <video src="blob:nodedat..." is not Working, so I am doing something wrong for sure
Can you help me uderstand what is wrong ?

How can I import an image from the express server to the client (in React)

I'm trying to show an image in react, which is neither a local image (in the client) nor an external image from the web but an image that is in the node.js express server (and I don't want to call it as if it was an external image, because the domain could change and it just doesn't seem right).
I know I can't just import it like I do with a local image in the client because we're speaking about different localhosts. I did try this:
loadImage = async (imageUrl) => {
const response = await fetch(`/api/images/${imageUrl}`);
const data = await response.json();
this.setState({ image: data });
}
componentDidMount() {
const { imageUrl } = this.props;
try {
this.loadImage(imageUrl);
} catch(error) {
console.log("Hay un error: " + error);
}
}
render() {
const { image } = this.state;
return(
<div>
<div>
<img alt="dontknowyet" className="blog-list-image" src={image} // and so on...
{image} does receive the correct path, but the image won't load and the console throws this error:
Not allowed to load local resource: file:///C:/Users/Dafna/Desktop/adrian/proyectos/esteticand/img/t4.jpg
So how can I make it work? and in case that I need to import the image file instead of just the link, how can I do that? (I can't update the state with an image...)
In order to access the path of the image it has to be done through the express server.
For example, if the (backend) server is running on port 4500 and the image is in a folder called images, and the express variable is called app, in the server file you have to use:
app.use(express.static('images'));
and then the image can be accessed in http://localhost:4500/nameoftheimage.jpg.
Do you have the api running on the same port as the React app?
You usually would make them run on different ports. Maybe it's got something to do with it.

Uncaught TypeError: fs.readFile is not a function

Node.js, Webpack
In this project using webpack, where installed FS.
This code need to read file, but returns error "Uncaught TypeError: fs.readFile is not a function"
const bookForm = document.querySelector(".book-form");
const select = document.querySelector(".select"); const fs = require("fs");
export function abc() { bookForm.addEventListener("submit", e => {
console.log(select.options[select.selectedIndex].text);
e.preventDefault();
fs.readFile("file.txt", function(error, data) {
console.log("file read");
if (error) throw error;
console.log(data); });
}); }
You cannot import the fs module in the browser, because the browser environment does not have access to the user's file system. fs is only available in the Node.js context (on the server) but not on the client (browser).
If you want to send files from the browser to the server, you can use <input type="file"> and let the user manually select the files they have to send. If you want to send a server file's contents to the browser, you can use HTTP communication (AJAX) or you can render it's content in a server-side computed HTML template.
Within your config file you can set the way in which assests like your txt file is uploaded. Then you simply use require('file.txt') to load it - no need to use fs.

Read file using in vue template

I need to read a file from the system in using vue.js
Something like:
import fs from "fs";
var fs = require("fs");
fs.readFile("path");
I Have an error with importing fs. what am I doing wrong?
I'm using Axios for this purposes like this:
axios.get('/' + 'settings.json').then(response => {
console.log(response.data);
//do anything you want with response.data (content of the file)
})
Your file must be in a public folder

Use server to download image and serve to frontend

I'm running into a CORS issue trying to pull images from S3 (Converting Image URL to base64 - CORS issue).
I'm just using the images for a few seconds while I am generating a PDF file. Is there a way that I can have Meteor download the image and serve for just a few seconds so that I can get around the CORS problem?
I can't have Meteor just serve the images all the time since there are a ton of them and they change for the different reports.
I ended up getting around the CORS issue by doing this:
import { request } from "meteor/froatsnook:request";
Meteor.methods({
convertImage: function(imageUrl) {
try {
var result = request.getSync(imageUrl, {encoding: null});
return 'data:image/png;base64,' + new Buffer(result.body).toString('base64');
} catch(e) {
throw new Meteor.Error("cant-download", "Error: Can't download image.");
}
}
});

Resources