Failed to upload image file in post man - node.js

//I have already on allow reading files outside working directory in postman and also change my image file path from desktop to the postman user file but it does not work
//answer-->answer
//error screenshots-->
cmd
cmd prompt error screenshot
postman error screenshot
const formidable=require("formidable");
const {errorHandler}=require('../helpers/dbErrorHandler');
const _=require("lodash");
const fs=require('fs');
const Product=require("../models/product");
exports.create=(req,res)=>{
let form = new formidable.IncomingForm();//IncomingForm is a method of Formidable package and form data sent from react/postman
form.keepExtensions=true;//whatever image type we getting extenion will be there
form.parse(req,(err,fields,files)=>{
if(err)
{
return res.status(400).json({
error:"image could not be uploaded"
})
}
let product=new Product(fields);//fields-->like name,description etc
if(files.photo)//for photo & files.photo means user sent photo
{
product.photo.data=fs.readFileSync(files.photo.filepath);
product.photo.contentType=files.photo.mimetype;
}
product.save((err,result)=>{
if(err)
{
return res.status(400).json({
error:errorHandler(err)
})
}
res.json(result);
})
})
};

To sum up. The solution was to set the content-type header in postman request to multipart/form-data

Related

Telegram Bot - How to upload local files with absolute/ dynamic URL

I'm trying to send photos through telegram bot using 'sendPhoto' method with relative url (Image at file level). I'm not using any library, here is my call function:
let axiosImage = async (chatId, caption, res) => {
try {
await axios.post(`${TELEGRAM_API}/sendPhoto`,
{
headers:{'Content-Type': 'multipart/form-data'}
},{
body: {
'chat_id': chatId,
'caption': caption,
'photo': './image.jpeg'
}
})
return res.send()
} catch (e) {
console.log('\nSTATUS RESPONSE: ' + e.response.status)
console.log('\nMESSAGE RESPONSE: ' + e.response.statusText)
}}
but I'm getting this message back: {"ok":false,"error_code":400,"description":"Bad Request: there is no photo in the request"}
I tried with a web url and it sends normally.
What could I be missing? Do I have to upload the local images in some repository?
I had a similar issue recently, I managed to solve the problem using form-data npm package and built-in fs module.
const FormData = require('form-data');
const fs = require('fs');
const axiosImage = async(chatId, caption, res) => {
try {
const formData = new FormData();
formData.append('chat_id', chatId);
formData.append('photo', fs.createReadStream('./image.jpeg'));
formData.append('caption', caption);
const response = await axios.post(`${TELEGRAM_API}/sendPhoto`, formData, {
headers: formData.getHeaders(),
});
return res.send();
} catch (err) {
console.log(err);
}
}
From the Telegram api docs
If the file is already stored somewhere on the Telegram servers, you don't need to reupload it: each file object has a file_id field, simply pass this file_id as a parameter instead of uploading. There are no limits for files sent this way.
Provide Telegram with an HTTP URL for the file to be sent. Telegram will download and send the file. 5 MB max size for photos and 20 MB max for other types of content.
Post the file using multipart/form-data in the usual way that files are uploaded via the browser. 10 MB max size for photos, 50 MB for other files.
What you want to send is a file via file upload (3.). This is the answer to what you are trying to achieve:
https://stackoverflow.com/a/59177066/4668136

Node.Js wont Upload file to Directory

I want to simulate an upload in Node.js REST api.
I want to make the REST api upload the files to a directory and then save the URL of the saved file to the database table.
For some reason, I dont know of , he just tells me , "No Files uploaded" But looking thru, everything seems okay.
I am testing thru Postman, so thats where i seem to be getting the output and what it tells me.
My code is looking like this:
app.post('/api/createpost', function (req,res){
if(!req.files) return res.status(400).send('No Files uploaded');
const {foo} = req.files;
const uploadTo = `postimages/${foo.name}`;
foo.mv(uploadTo, (err) =>{
if(err) return res.status(500).send(err);
//push data to mysql Db
var username = req.body.username;
var imgUrl = 'http://localhost/'+uploadTo;
var post = req.body.post;
dbConn.query('INSERT INTO instagramclonedbposts SET ?', [username, imgUrl, post], function(error, results, fields){
if(error) throw error;
return res.send({error:false, message: 'Post Created'});
});
});
});
Testing in Postman, I have this :
Could there be something i am missing?

nodejs: Retrieving base64 Images from Mongodb using Postman

Looking for help on Uploading and Retrieving Images from MongoDb using multer.
My front end is ReactNative.(Not sure if this is needed but just to be sure.)
Multer
Problem: After looking and following tutorials i'm able to encode my path to base64 and upload it to my DB but now i'm confused how to retrieve the file from my DB. I saw some tutorials about decoding it from base64 but I don't quite understand how do I go about retrieving an image and displaying it in postman. (I tried looking but haven't found anything that gives me an answer. I'm sorry if this is a duplicated question. If you could point me in a direction or give me some advice I would be really greatful.)
**POST**
route.post("/sad", upload.single("image"), (req, res, next) => {
console.log(req.file);
const img = fs.readFileSync(req.file.path);
const img_enc = img.toString('base64');
const obj = {
usrImage: {
data: new Buffer.from(img_enc, 'base64'),
contentType: "image/jpg",
},
};
console.log(obj);
const newAccout = new account(obj);
newAccout.save();
});
**RETRIEVE**
route.get('/sad',(req,res)=>{
img.find({}).then((img)=>{
res.json(img)
//How do decode my buffer to show an image in Postman?
})
}
)
I am trying to create a userprofile where a username,password and image is saved. If you can help save an Image and then retrieve it from my accounts collection.
Hey I would advise that you start using a 3rd party for file upload like cloudinary very good way of managing files i.e images or video...
I am not that well of with multer but I can give a quick code example using Formidable does the same work as multer
Before you can start you'd need to make an account on cloudinary.com(don't worry its free)
Code below is how you could handle file upload
const Formidable = require("formidable"); //Meant for body parsing
const cloudinary = require("cloudinary").v2; // file uploader
//This below is your connection/configuration to get access to your cloudinary account so cloud_name, api_key and api_secret you'll get in your home dashboard(Cloudinary)
cloudinary.config({
cloud_name: process.env.CLOUD_NAME,
api_key: process.env.API_KEY,
api_secret: process.env.API_SECRET,
});
router.post('/api/file-upload', (req, res)=>{
const form = new Formidable.InconmingForm();
form.parse(req, (error, fields, files)=>{
const {file} = files
cloudinary.uploader.upload(file.path, {folder:"/"}, (err, res)=>{
const file_url = res.secure_url //This would be the url for your file given back by cloudinary
})
})
})
This script should upload your file and the file_url will be having the url of the file that you upload having ssl then after that you can now continue saving to mongoDB
Cloudinary docs for NodeJS
https://cloudinary.com/documentation/node_integration
Nice clear and understandable docs
Shameless plug
If you get lost you can check this video out on YouTube that I made handling file upload with cloudinary then save url given back to mongoDB
https://youtu.be/mlu-tbr2uUk
First call api find one
you will need fs module to complete following query
const fs = require('fs');
let data = await db.user.findOne({
where: {
id = req.body.id
}
})
// _________________ base 64 string data from findone query data
// |
let buff = new Buffer(data.image, 'base64');
let name = name.jpeg
let path = `tmp/${name}`; // <--- destination and file name you want to give to your file
fs.writeFileSync(path, buff);// < --this will write file to given path
fs.readFile(path, function (err, content) {// <------to send file in postman response
if (err) {
res.writeHead(400)
console.log(err);
res.end("No such image");
} else {
//specify the content type in the response will be an image
res.writeHead(200);
res.end(content);
}
});
fs.unlink(path, (err) => { // <-----to delete file from tmp directory
if (err) {
console.log(err)
}
})
Try this and switch to preview tab in postman.
I haven't tried it but maybe it helps.
route.get('/sad',(req,res)=>{
img.find({}).then((img)=>{
res.setHeader('contentType','image/jpg').send(img)
})
})

How do I create a file in express and node on my server and then download it to my client. I am using NextJS for my frontend and backend

How do I create a file in express and node on my server and then download it to my client. I am using NextJS for my frontend and backend. I am confused on how I would download the file on the front end after the file is created on the root of the server folder. Since I am using React for my frontend whenever I try to visit that filepath it tries to take me to a page instead of the file
Here is what I have in my express route in node
var xls = json2xls(json, {
fields
});
// If there isn't a folder called /temp in the
// root folder it creates one
if (!fs.existsSync('./temp')) {
fs.mkdirSync('./temp');
}
const fileName = `temp/${req.user.first_name}${req.body._id + Date.now()}.xlsx`
// fs.writeFileSync(fileName, xls, 'binary');
fs.writeFile(fileName, xls, 'binary', function (err, result) {
if (err) {
return console.log(err);
}
console.log(result, 'this is result')
});
Here is what I have on my frontend
axios.post('api/download',payload)
.then(res => {
const link = document.createElement('a');
link.href = res.data.url;
link.download
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
})
.catch(err => {
throw err
})
Can you make request with GET on api, and.
Make request with GET.
Make temp directory to be static resources directory:
app.use(express.static('temp')); // app is your express instance.
// Maybe you have to correct temp's path
Response the post request with file url data
fs.writeFile(fileName, xls, 'binary', function (err, result) {
if (err) {
return console.log(err);
res.status(500).json({err});
}
console.log(result, 'this is result');
res.json({url: 'http://localhost:8080/temp/' + fileName}); // res is response object of you router handler.
// Maybe you have correct the server address
});
On other way, you can send the xls binary direct to client, in the client you create a BLOB object from the response, then create download link for the blob object.

Unable to post data or send a file using axios and form-data

I am trying to post data from my nodejs app to a an endpoint.
I tested sending some data to that endpoint using Postman and all works fine, I got the posted data and all got printed to the console.
but I am always getting empty post data at my endpoint when sending from my nodejs using axios.
here is my code:
const FormData = require('form-data');
const axios = require('axios');
function send_to_test() {
const endpoint = 'http://localhost:5000/test';
const form = new FormData();
form.append('string_var', 'some string');
form.append('integer_var', 100);
axios.post(endpoint, form, { headers: form.getHeaders() }).then((res) => {
console.log(res.data);
});
};
and here is my endpoint (I am using express js server):
app.post('/test', function(req, res) {
console.log(req.body);
res.json({
status: 'success'
});
});
Unable to get this working, please advise and thanks in advance.
You need to setup a form parser at the your endpoint. You can make use of formidable. code for reference:
const form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
if (err) {
return res.status(400).json({ error: err.message });
}
res.json({
status: 'success'
});
}
I hope it gives you better picture!

Resources