I can't find a simple solution how to display an image on my website.
I can read it in my node js backend but it will download the file instead of placing in my img tag.
Do you have a simple solution for that?
Thank you very much!
HTML
let cell6 = document.createElement("td");
cell6.innerHTML = `<img src={http://localhost:4001/getImage/pexels-cottonbro-4065175.jpg}></img>`;
NODE JS
const fs = require("fs");
require("dotenv").config();
module.exports = (req, res) => {
fs.readFile(
`../backend/images/${req.params.id}`,
function (err, image) {
if (err) {
throw err;
}
console.log(image);
res.send(image);
}
);
};
The problem you face here is not how you read the data, it's how you send the data to Frontend.
First of all, you need to set the headers properly that the frontend (receiver) understands that it's an image and doesn't download that but to show it.
Modified your code here:
const fs = require("fs");
require("dotenv").config();
module.exports = (req, res) => {
fs.readFile(
`../backend/images/${req.params.id}`,
function (err, image) {
if (err) {
throw err;
}
console.log(image);
res.setHeader('Content-Type', 'image/jpg');
res.setHeader('Content-Length', ''); // Image size here
res.setHeader('Access-Control-Allow-Origin', '*'); // If needs to be public
res.send(image);
}
);
};
Related
const xml2js = require('xml2js');
const fs = require('fs');
fs.readFile('https://www.tcmb.gov.tr/kurlar/today.xml', (err, data) => {
if(err) console.log(err);
var data = data.toString().replace("\ufeff", "");
xml2js.parseStringPromise(data, (err, res) => {
if(err){
console.log(err);
} else {
console.log(res);
}
});
});
This is my code in nodejs I try to get data on a https link with xml2js first by using the way it says in the npm page pf xml2js it gives some error and when I chechk on web I find solution of using with fs but still geting this error
I know the directory exists because if you go to link used in code it shows something but in code just gives error if someone can help I will be very happy
fs can only access file in your system, you should request the URL using http/https or even better try axios
const axios = require('axios')
axios.get('https://www.tcmb.gov.tr/kurlar/today.xml').then((response) => {
const data = response.data
xml2js.parseString(data, (err, res) => {
if(err){
console.log(err);
} else {
console.log(res);
}
})
})
I have many files which are stored in upload_file collection in mongodb and they have relations with related content types. However when I open Strapi CMS UI, I cannot see the file attached on its content type.
I am using Strapi v3.4.6 — Community Edition.
In the first picture is showing the my one of upload_file collection item. Its relation is shown in red circle.
In the second picture is showing the my main content type collection item. You see that its id and upload_file rel id is matching.
But in Strapi UI, this file is not linked to model. The file exists in file system of Strapi. However it is not visible
I can add this file manually, but is there any quick way to do this?
You need to migrate the database. We solved with a basic script.
Run http://localhost:3000/migrate
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017";
var dbName = "YOURDBNAME";
const express = require('express')
const app = express()
const port = 3000
var _db;
var _dbo;
var tables = {
"table1": "TabLE1",
"table2": "TABle2",
}
app.get('/migrate', (req, res) => {
res.send('Started!')
_dbo.collection("upload_file").find({}).toArray(function(err, result) {
if (err) throw err;
result.forEach(function (item) {
if (item.related.length > 0) {
var related = item.related[0];
var query = { '_id': related.ref };
var newvalues = { $set: {} };
newvalues.$set[related.field] = item._id;
var tableName = related.kind.toLowerCase();
_dbo.collection(tables[tableName]).updateOne(query, newvalues, function(err, res) {
if (err) throw err;
console.log(res != null ? res.ops : null);
});
}
})
// db.close();
});
})
MongoClient.connect(url, function(err, db) {
if (err) throw err;
_dbo = db.db(dbName);
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
// Run http://localhost:3000/migrate
When uploading your image to strapi make sure your formData has these fields
const formData = new FormData();
formData.append('files', image);
formData.append('ref', 'contentTypeName');
formData.append('refId', dataItemId);
formData.append('field', 'image');
I have stored the file after uploading it to the downloads folder in my project directory.
I want to download that saved file from the frontend.
When I click on the download button, it doesn't fetch the file.
And when I go to http://localhost:5000/download on the express app, I got this error message
Error: Can't set headers after they are sent.
Express Server Code:
app.get('/download', (req, res) => {
res.send('file downloaded')
const file = './downloads/output.yml';
res.download(file, 'openapi.yml', (err) => {
if (err) {
console.log(err)
} else {
console.log('file downloaded')
}
});
});
Frontend App code:
HTML:
<button class="download-btn">download</button>
Script:
const handleDownload = async () => {
const res = await fetch("https://cors-anywhere.herokuapp.com/http://localhost:5000/download");
const blob = await res.blob();
download(blob, 'output.yml');
}
downloadBtn.addEventListener('click', handleDownload);
Folder Structure:
Update:
Server.js
const uploadFiles = async (req, res) => {
const file = await req.files[0];
console.log(file)
postmanCollection = file.path;
outputFile = `downloads/${file.filename}.yml`
convertCollection();
res.json({ message: "Successfully uploaded files" });
}
app.post("/upload_files", upload.array("files"), uploadFiles);
Anyone please help me with this.
You are already using res.send ,which sends the response headers back to client ,which ends the request response cycle ,and when you try to do res.download it throws error. Use instead
app.get('/download', (req, res) => {
const file = './downloads/output.yml';
res.download(file, 'openapi.yml', (err) => {
if (err) {
console.log(err)
} else {
console.log('file downloaded')
}
});
});
res.send('file downloaded')--->remove this line
You need to update your js code as well
const handleDownload = async () => {
const res = await fetch("https://cors-anywhere.herokuapp.com/download"); //http://localhost:5000--->this is not required
const blob = await res.blob();
download(blob, 'output.yml');
}
downloadBtn.addEventListener('click', handleDownload);
Client code:
var data = new FormData();
data.append(fileName, blob, 'test.html');
fetch('http://localhost:3000/', {
method: 'POST',
headers: {
},
body: data
}).then(
response => {
console.log(response)
}
).then(
success => {
console.log(success)
}
).catch(
error => {
console.log(error)
}
);
Server code:
router.post('/', urlencodedParser, function(req, res, next) {
const body = req.body;
console.log(body);
res.send(`You sent: ${body} to Express`);
});
I am sending a blob in the body of a post request. When I send it to the server I want the server to download the file from the body of the request. How can i download this file? Or is there a simpler way to upload from client?
If you can utilize an NPM package formidable, there appears to be a solution at: https://www.w3schools.com/nodejs/nodejs_uploadfiles.asp
Once you have the file received, you can use the fs module to save and store in server
May it can solve your problem.
const fs = require('fs');
let directory = '/temp/data'; // where you want to save data file
router.post('/', urlencodedParser, function(req, res, next) {
const body = req.body;
console.log(body);
fs.writeFile(directory, body, function(err) {
if(err) {
return console.log(err);
}
console.log("File has been saved");
});
res.send(`You sent: ${body} to Express`);
});
This solved my answer - https://attacomsian.com/blog/uploading-files-nodejs-express, which basically uses a middleware to do the upload.
This was basically like:
const x = 6;
console.log(x);
Error: value is f'd up
const x = 6;
magic.valueParse(x);
console.log(x);
6
Also, i would like to point out how bodyParser cannot be used for multipart data. It is mentioned on the official docs, but even responses I get seem to point to bodyParser. So I thought I'd re-iterate that.
I am trying to read a file using node's readFile method and then send it as response so that user can download it.
This is my code:
async function(req, res, next) {
const query = { id: req.params.id };
// #ts-ignore
const fileURL = await Patient.findOne(query).select('retinaReportURL -_id');
// #ts-ignore
const splittedPath = fileURL.retinaReportURL.split('\\');
const fileName = splittedPath[splittedPath.length-1].split('.')[0] + '.pdf';
const filePath = path.join(__dirname, '..', '..', 'Invoices', fileName);
fs.readFile(filePath, (err, _data) => {
if (err) {
return next(new APIError('Unable to fetch file at the moment please try again later', 500))
}
res.send(data);
});
}
Now my file path is proper with a valid PDF inside the Invoices folder.
But the, when the file is getting downloaded, am facing two issues:
The .pdf extension is not there.
The file name by which it's get downloaded is the id I am passing as request param.
I tried setting a response header to text/pdf but no luck.
What am I doing wrong here??
Express has a helper for this to make it easy for you,
I assume you have following path,
const fileName = splittedPath[splittedPath.length-1].split('.')[0] + '.pdf';
const filePath = path.join(__dirname, '..', '..', 'Invoices', fileName);
app.get('/download', function(req, res)
{
res.download(filePath); // Set file name with its path
});