I am using node and express for backend and Mongo DB for storage.I am using multer middleware for storing image,i got a problem and the problem is when i store an image from local host it get saved in my backend and also shown in database,but when i deploy the same api on heroku or any other app the image is shown in database but it is not stored in my backend.I have tested the code on postman,what may be the issue?
Following below is my code on node js:
router.use(express.static(__dirname + 'public'));
let storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
}
})
let upload = multer({ storage: storage })
router.post('/fellows-details', upload.single('image'), async (req, res) => {
const { error } = FellowsDetails(req.body);
if (error) return res.status(400).send({ message: error.details[0].message });
const fellow = new fellowdetails({
name: req.body.name,
details: req.body.details,
image: req.file.filename
})
try {
fellow.save()
res.status(200).send({ message: 'fellows detail saved successfully' })
} catch (err) {
res.status(400).send(err);
}
})
It will become easy to store files after converting in string
you just have to convert string in image in your frontend
convert image in to base64 string using this code in your api and also don't forgot to delete file from upload folder
"img": new Buffer.from(fs.readFileSync(req.file.path)).toString("base64")
to delete the file
let resultHandler = function (err) {
if (err) {
console.log("unlink failed", err);
} else {
console.log("file deleted");
}
}
fs.unlink(req.file.path, resultHandler);
at your routes import multer
`multer const multer = require('multer');
const upload = multer({ dest: __dirname + '/uploads/images' });`
Add upload.single('img') in your request
router.post('/fellows-details', authorize([Role.ADMIN, Role.USER]),
upload.single('img'), usersController.fellowsdetails);
The filesystem on Heroku is not suitable for the persistent storage of data. The Heroku filesystem is ephemeral - that means that any changes to the filesystem whilst the dyno is running only last until that dyno is shut down or restarted. Each dyno boots with a clean copy of the filesystem from the most recent deploy
You can't store files on Heroku. Heroku automatically removed your uploaded files. You have to use external services like Amazon S3 or Azure Blob Storage.
https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-node-examples.html
https://learn.microsoft.com/en-us/javascript/api/#azure/storage-blob/blockblobclient?view=azure-node-latest
If you don't want to set up an account with AWS to create an S3 bucket we also have add-ons here that handle storage and processing of static assets https://elements.heroku.com/addons
var dateString = Date.now();
var storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, './uploads/')
},
filename: (req, file, cb) => {
cb(null, dateString+'_'+file.originalname)
}
});
var maxSize=3 1000 1000;
var upload = multer({ storage: storage,
limits: { fileSize: maxSize }})
var upload = multer({ storage: storage , limits: { fileSize: maxSize }});
app.post("/fileupload", upload.single("fileToUpload"), function (req, res) {
console.log(req.file.originalname)
var uploaded = "http://localhost:4001/"+dateString+'_'+req.file.originalname;
console.log(uploaded)
res.json({status: 200,msg:'File saved successfully',data:uploaded});
});
Related
I Am trying to store images on Heroku server ./public.uploades folder but when I try to get images I get 404 not found is there any way to store images in Heroku other AWS s3
const storage = multer.diskStorage({
destination:function(req,file,cb){
cb(null,"./public/uploades") //storage confg
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
})
const upload = multer({ storage:storage,limits: { fileSize: 5000000 }});
app.get("/fetchimage/", (req, res) => {
const file = req.query.file
const fileLocation = path.join('/public/uploades', file);
res.sendFile(__dirname +fileLocation)
})
Heroku dose not allow any file excluding git. However you can use https://cloudinary.com for image upload its free.
I have a script that allows me to upload files into a folder using React on the frontend and Node on the backend.
I have a folder named client and another named server. When I click on upload file, the file is uploaded.
So what I did is create a new project and moved just the backend, keeping client in the old one. Now, when I click on upload image, I get this error and I don"t know why:
Maybe there is something wrong with Multer?
Code:
server
const path = require("path");
const multer = require("multer");
const storage = multer.diskStorage({
destination: "uploads/",
filename: function (req, file, cb) {
cb(null, "IMAGE-" + Date.now() + path.extname(file.originalname));
},
});
const upload = multer({
storage: storage,
limits: { fileSize: 1000000 },
}).single("file");
exports.filesU = (req, res) => {
upload(req, res, (err) => {
console.log("Request ---", req.body);
console.log("Request file ---", req.file);
//Here you get file.
/*Now do where ever you want to do*/
if (!err) return res.json({ success: true, url: res.req.file.path });
});
};
client
let formdData = new FormData();
const config = {
header: { "content-type": "multipart/form-data" },
};
formdData.append("file", files[0]);
console.log(formdData);
Axios.post(
"http://localhost:4000/api/chat/uploadfiles",
formdData,
config
)
I am working on a project and i need to upload and save image to MongoDB. I using NodeJS as backend and Angular Material for frontend.
I am writing the node and angular in TypeScript. How this upload and save can happen. I want also to know how I can reed and display them.
Check Multer
example of use
store.js
import multer from 'multer';
const storage = multer.diskStorage({
destination: function (req, file, cb) {
const path = process.cwd() + '\\uploads';
cb(null, path);
},
filename: function (req, file, cb) {
cb(null, `file-${Date.now()}.${file.originalname.split(/[.]+/).pop()}`);
}
});
export const UploadHandler = multer({
storage: storage,
fileFilter(req, file, callback, acceptFile) {
if (['image/png'].indexOf(file.mimetype) === -1) {
return callback(new Error("This File Is Not Supported"), false);
}
return callback(null, true);
}
});
app.js
import store from './store';
app.post('/upload', store.array('files', 1), function (req, res, next) {
if(req.files && req.files.length > 0) {
// files uploaded successfully
}
});
This question has been asked before. But as I have failed to get solution for my problem, I am asking again.
I am trying to upload image for a property using multer package as form-data so I can store other data and path of image in the database. I am using node express.
My api--
api.post('/service', upload.single('servicesImage'),
(req, res, next) => {
console.log(req.file);
Company.find({ domain: req.headers.domain },
(err, company) => {
const servicecontent = new Servicecontent({
description: req.body.description,
created_at: Date.now(),
created_by: req.body.user_id,
company_domain: req.headers.domain,
company_uuid: company[0].uuid,
image: req.file.path,
})
servicecontent.save(err => {
console.log(err);
});
res.json({ status: "success" });
});
});
I watched a tutorial, and from that I added these codes to upload image and other options--
const storage = multer.diskStorage({
destination: function(req, file, cb){
cb(null, './src/uploads/');
},
filename: function(req, file, cb){
cb(null, new Date().toISOString()+ file.originalname);
},
});
const upload = multer({storage: storage, limits:{
fileSize: 1024*1024*5
},
fileFilter: fileFilter
});
const fileFilter = (req, file, cb) =>{
if(file.mimetype=== 'image/jpeg' || file.mimetype=== 'image/png'){
cb(null,true);
}else{
cb(null,false);
}
};
Now when I send data and image through Postman , from console.log(req.file)
I get valid data as I saw from the tutorial. Api responds without any errror, and in database I can see all datas are stored including image path. But the issue I am facing is that in src/upload folder is empty, no image is uploaded.
N.B. -- I am using linux 18.04 Os, and fs package can't be installed. So src/upload folder wasn't creating when I were sending req, so I created this directory from folder.
Edit: I can upload image with this code now, I don't exactly know why this wasn't working earlier. I should close this question, if possible.
I can upload image with this code now, I don't exactly know why this wasn't working earlier. I should close this question, if possible.
Try this to store images.
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/')
},
filename: function (req, file, cb) {
console.log(file);
cb(null, makeid(3) + file.originalname)
}
})
var upload = multer({ storage: storage })
`
I have uploaded files of different types(image, pptx, video and docx) using Multer in the folder named 'uploads'.
var storage = multer.diskStorage({ //multers disk storage settings
destination: function (req, file, cb) {
cb(null, './uploads/');
},
filename: function (req, file, cb) {
var datetimestamp = Date.now();
cb(null, file.originalname);
}
});
var upload = multer({ //multer settings
storage: storage
}).single('file');
/** API path that will upload the files */
app.post('/upload', function(req, res) {
upload(req,res,function(err){
if(err){
res.json({error_code:1,err_desc:err});
return;
}
res.json({error_code:0,err_desc:null});
});
});
Now the uploaded files are being stored in 'uploads' folder like /uploads/demo.pptx
I need to fetch these and send the filepath or url of the stored files and send as a response to client so they can access to watch or download it.
Usually, files stored in DB when you need to do more than just serve them and upload new files. For this proposes, you could save only file's metadata to DB(such as size, type, path, name). However if you for some reason still need to store files in DB, MongoDB have GridFS component and provides a documentation about working with this component.
you can do something like this:-
var mongojs = require('mongojs');
var db = mongojs(//credential here);
var uploaded_file=db.collection("uploaded_file");
var storage = multer.diskStorage({ //multers disk storage settings
destination: function (req, file, cb) {
cb(null, './uploads/');
},
filename: function (req, file, cb) {
var datetimestamp = Date.now();
cb(null, file.originalname);
}
});
var upload = multer({ //multer settings
storage: storage
}).single('file');
/** API path that will upload the files */
app.post('/upload', function(req, res) {
upload(req,res,function(err){
if(err){
res.json({error_code:1,err_desc:err});
return;
}else{
uploaded_file.insert(res.file,function(err, saved) {// i am asuming res.file have the information you needed to send
if(err){
console.log("Unexpected error occurred during insertion in database:"+err);
}else{
res.send({error_code:0,file_info:res.file});
res.end();
}
});
}
});
});