Getting file from hash in js-ipfs - ipfs

I'm running the script below and using an ipfs node to upload and get a file using its hash, but the ipfs cat function only returns the path of the file from the hash, not the content.
const node = new Ipfs()
node.once('ready', () => console.log('IPFS node is ready'))
$("#saveIt").click(function(){
var toStore = document.getElementById('fileInput').value
node.files.add(new node.types.Buffer.from(toStore), (err, res) => {
if (err || !res) {
return console.error('ipfs add error', err, res)
}
res.forEach((file) => {
if (file && file.hash) {
var newVar = file.hash
var newVar1 = newVar.slice(0, 23)
var leng = newVar.length
var newVar2 = newVar.slice(24, leng)
console.log(newVar1 + ' ' + newVar2)
mediachain.setUserFile($("#passwordSetter").val(), newVar1, newVar2)
node.files.cat(file.hash, (err, data) => {
if (err) {
return console.error('ipfs cat error', err)
}
document.getElementById('fileDisplayArea').innerText = data
})
} else {
console.error("Error: invalid file")
}
})
})
})
Does anyone have experience with js-ipfs and can help me out?

I had a similar problem with ipfs.
if you have hash already you can get the content this way.
const validCID = 'QmQFPQ5f94byxs7zvHMLJcx5WzThRhN4MfAF4ZisSXofKC'
ipfs.files.get(validCID, function (err, files) {
files.forEach((file) => {
console.log(file.path)
console.log("File content >> ",file.content.toString('utf8'))
})
})

Related

use common function output in multple files in node.js

I am new to programming...still self learning. I have below problem
I have below code in x.js file which I wish to reuse in same x.js file as well as in y.js file. both x.js and y.js are in controllers folder in a node.js project. The code is
''''''''
let indexmain = function(){
async.parallel({branch_count(callback) {
Branch.countDocuments({}, callback); documents of this collection},
customer_instance_count(callback) {
CustInstance.countDocuments({}, callback);
},
customer_instance_available_count(callback) {
CustInstance.countDocuments({ status:'Interested' }, callback);
},
}
);
return [branch_count, customer_instance_count, customer_instance_available_count];
''''''''
When used in below code inthe same file:
''''''''
const { body, validationResult } = require("express-validator");
const Branch = require('../models/brdetails');
const Customer = require('../models/custdetails');
const CustInstance = require('../models/custInstance');
const async = require('async');
exports.index = (req,res) => { (
branch_count = Indexmain[0],
customer_instance_count = Indexmain[1],
customer_instance_available_count = Indexmain[2]);
(err, results, next) => { if (err) { return next(err); }
res.render('index.jade', {error: err, data: results });
}
};
'''
There is no error, but page does not load at all. When checked with
'''
console.log("Indexmain is", Indexmain[0]);
'''
Output is "Indexmain is undefined".
What is to be done? Please help.

Nodejs: Can't post a string filed and image on the same request with Express and Mysql

I am using mutler to upload image with post request and also string data.
When I upload only the image with Postman or React, it is working, but when I send also the strings, it shows this:
undefined
TypeError: Cannot read properties of undefined (reading 'filename')
The string got saved to MySQL but not the image.
That's my code for the Multer:
let storage = multer.diskStorage({
destination: (req, file, callBack) => {
callBack(null, './public/images/')
},
filename: (req, file, callBack) => {
const mimeExtension = {
'image/jpeg': '.jpeg',
'image/jpg': '.jpg',
'image/png': '.png',
'image/gif': '.gif',
}
callBack(null, file.originalname)
}
})
let upload = multer({
storage: storage,
fileFilter: (req, file, callBack) => {
// console.log(file.mimetype)
if (file.mimetype === 'image/jpeg' ||
file.mimetype === 'image/jpg' ||
file.mimetype === 'image/png' ||
file.mimetype === 'image/gif') {
callBack(null, true);
} else {
callBack(null, false);
req.fileError = 'File format is not valid';
}
}
});
And that's my post request:
router.post('/', upload.single('image'), async (req, res) => {
try {
if (!req.file) {
console.log("You didnt upload a picture for your project");
}
const { title, about_the_project, project_link, user_id } = req.body
const projectnum = await SQL(`INSERT into project(title,about_the_project,project_link,user_id)
VALUES('${title}','${about_the_project}','${project_link}',${user_id}) `)
console.log(projectnum.insertId);
console.log(req.file && req.file.filename)
let imagesrc = 'http://127.0.0.1:5000/images/' + req.file && req.file.filename
await SQL(`UPDATE project SET image = '${imagesrc}' WHERE projectid = ${projectnum.insertId}`)
res.send({ msg: "You add a new project" })
} catch (err) {
console.log(err);
return res.sendStatus(500)
}
})
On React that's the code:
const PostNewProject = async () => {
let formData = new FormData()
formData.append('image', imgsrc)
const res = await fetch(`http://localhost:5000/project`, {
headers: { 'content-type': 'application/json' },
method: "post",
body: JSON.stringify({ title, about_the_project, project_link, languages, user_id }),formData,
// credentials: "include"
})
const data = await res.json()
if (data.err) {
document.getElementById("err").innerHTML = data.err
} else {
console.log(data);
document.getElementById("err").innerHTML = data.msg
}
}
And the input for the image upload
<Input
type='file'
name='image'
sx={{ width: '25ch' }}
onChange={(e) => setImgsrc(e.target.files[0])}
/>
Thank you for your help!
You did not write a comma after the filename and before the callback function in the Multer.
I think you should check you exports too.

TypeError: Cannot read properties of undefined (reading 'filename') in multer

I have a very similar problem with respect to this fellow community contributor. How do i produce multer error message in my postman I followed through the comments made by other users and it was successful! However, when i tried to post a image that is a jpg formatted image( which i managed to do before the editing), it now fails and state that TypeError: Cannot read property 'filename' of undefined.
// multer.js file
successfully setup multer
**please tell me why this error comes on my code and give me a solution**
const multer = require('multer');
const storage = multer.diskStorage({
fileSize: 1024*1024*2,
destination: function (req, file, cb) {
cb(null, './uploads')
},
filename: function (req, file, cb) {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
cb(null, file.fieldname + '-' + uniqueSuffix)
}
})
const filter = function (req, file, cb) {
if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
cb(null, true);
} else {
cb(new Error('unsupported files'), false)
}
}
var upload = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 5
},
fileFilter : filter
});
module.exports = upload;
//controller.js file
//create function
here's my logic to create a new user
exports.create = (req, res, next) => {
if (!req.body) {
res.status(400).send({ message: "content cannot be empty !!" })
return
}
let data = { name: req.body.name, description: req.body.description, brand_url:
req.body.brand_url, image_file: req.body.file.filename }; getting error here
let sql = "INSERT INTO influencer SET ?";
db.query(sql, data, (err, results) => {
if (err) throw err;
console.log('data inserted succesfully')
res.redirect('/admin');
});
}
//api.js file
//post API
router.post('/api/create', upload.single('image') ,controller.create) //when I am
sending file its throw back error undefined filename
Please make sure you have added enctype="multipart/form-data"
<form action="/api/create" enctype="multipart/form-data" method="post">
I have tested the codes & found the problem.
exports.create = (req, res, next) => {
if (!req.body) {
res.status(400).send({ message: "content cannot be empty !!" })
return
}
let data = {
name: req.body.name,
description: req.body.description,
brand_url: req.body.brand_url,
image_file: req.file.filename
}; // Remove "body", I have tested, it works well.
let sql = "INSERT INTO influencer SET ?";
db.query(sql, data, (err, results) => {
if (err) throw err;
console.log('data inserted succesfully')
res.redirect('/admin');
});
}

Error In Multer When Trying To Upload A Image

Currently new to multer, so here's my problem:
I kept getting the MulterError: Unexpected field as the output when i try to POST the jpg image into mysql. Can anyone see whats the bug in my code? Currently im trying to make a error message when an image of more than 1MB is uploaded.
var multer = require('multer');
var path = require('path');
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + new Date().toISOString() + '-' + path.extname(file.originalname));
}
});
var upload = multer({storage: storage});
// Endpoint 13 (EXTRA FEATURE 1)
const fileFilter = (req, file, callback) => {
if(file.mimetype === 'image/jpg') {
callback(null,true);
}
callback(null,false);
}
var uploadFromDesktop = multer({
storage:storage,
limits: {
fieldSize: 1024 * 1024
},
fileFilter: fileFilter
});
app.post("/upload/", upload.single('productImage'), (req, res, next) => {
uploadFromDesktop(req,res),(error) => {
console.log(error);
if (error) {
if (error.code === 'LIMIT_FILE_SIZE') {
} else {
res.status(500).send({ 'status': status, 'error':error})
}
} else {
var temp = req.file.path;
var file = uploadDir + req.file.originalname;
var source = fs.createReadStream(temp);
var destination = fs.createWriteStream(file);
source.pipe(destination);
fs.unlink(temp);
source.on('end',function () {
var result = {
'status': 'success',
'file': file
}
fs.chmod(file,0777);
res.send(result);
})
source.on('error', function (error) {
var result = {
'status': 'Fail',
'error': error
};
res.send(result);
})
}
}
})
Try with fileSize:
limits: {
fileSize: 2 * 1024 * 1024 // 2 MB}

how to import excel file in to mysql using nodejs

I am trying to import data in excel file to mysql just like row colon using nodejs are there any references i can learn or any module in nodejs that does my work or any sample code
I used Npm packages "xlsx-to-json-lc" and "xls-to-json-lc" to import excel file to json directly without converting to csv. Hope this helps...
var storage = multer.diskStorage({ //multers disk storage settings
destination: function (req, file, cb) {
cb(null, './uploads/')
},
filename: function (req, file, cb) {
var datetimestamp = dateFormat(new Date(), "yyyy~mm~dd h~MM~ss");
cb(null, '`enter code here`templete' + '-' + datetimestamp + '.' +
`enter code here`file.originalname.split('.')[file.originalname.split('.').length - 1])
filename = file.fieldname;
}
});
var upload = multer({ //multer settings
storage: storage,
fileFilter: function (req, file, callback) { //file filter
if (['xls', 'xlsx'].indexOf(file.originalname.split('.')[file.originalname.split('.').length - 1]) === -1) {
return callback(new Error('Wrong extension type'));
}
callback(null, true);
}
}).single('file');
var exceltojson;
upload(req, res, function (err) {
if (err) {
res.json({ error_code: 1, err_desc: err });
return;
}
if (!req.file) {
//res.json({ error_code: 1, err_desc: err });
return;
}
if (req.file.originalname.split('.')[req.file.originalname.split('.').length - 1] === 'xlsx') {
exceltojson = xlsxtojson;
} else {
exceltojson = xlstojson;
}
try {
exceltojson({
input: req.file.path,
output: null, //since we don't need output.json
//lowerCaseHeaders: true
}, function (err, result) {
if (err) {
return res.json({ error_code: 1, err_desc: err, data: null });
}
else {
console.log(result);
}
});
})