I have mostly configured my node backend to handle multi-part forms and it is saving my images to the correct directly. However the only part I can’t seem to get to work is the url address being posted into the photos text field in postgres. As I have yet to see this work I am not sure how it should look. I have tried changing the file type to BLOB / BYTEA (‘long’) and it looked like it populated with binary data but I am trying to just get the URL and store the file on my backend.
Should it be the fs.readFileSync line of my controller method that inserts this into the table? what does it look like I am doing wrong?
const article = sequelize.define("articles", {
articleID: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false
},
articleTitle: {
type: Sequelize.TEXT
},
articleContent: {
type: Sequelize.TEXT
},
articlePhotos: {
type: Sequelize.TEXT,
data: Sequelize.Buffer,
},
articleAuthor: {
type: Sequelize.INTEGER
},
articleType: {
type: Sequelize.INTEGER
}},
{
timestamps: false
}, {});
article.associate = function(models){
article.articleType.belongsTo(models.article, {
foreignKey: {name: 'articleTypeID', as: 'articleTypeID'}})
article.articleAuthor.belongsTo(models.userLogin, {
foreignKey: {name: 'userID', as: 'userID'}})
};
return article;
};
article.controller.js
exports.createArticle = (req, res) => {
try {
// article being added to the db
console.log("kuiogio", req.body)
article.create({
articleID: req.body.articleID,
articleTitle: req.body.articleTitle,
articleContent: req.body.articleContent,
articleAuthor: req.body.articleAuthor,
articleType: req.body.articleType,
photos: fs.readFileSync(
__basedir + "/assets/" + req.file.filename
),
}).then((article) => {
fs.writeFileSync(
__basedir + "/assets/" + article.articleTitle,
req.file.buffer
);
return res.send(`File has been uploaded.`);
// set user role to 1 to get basic user access on sign up
});
} catch (error) {
console.log(error);
return res.send(`Error when trying upload images: ${error}`);
}
};
multer
const multer = require("multer");
// config for multer to disk storage engine
const imageFilter = (req, file, cb) => {
if (file.mimetype.startsWith("image")) {
cb(null, true);
} else {
cb("Please upload only images.", false);
}
};
//sustscub timestamp prefix to stop duplicates
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, __basedir + "/assets/");
},
filename: (req, file, cb) => {
cb(null, `${Date.now()}-SustScub-${file.originalname}`);
},
});
// filter only allows images to pass
const uploadFile = multer({ storage: storage, fileFilter: imageFilter });
module.exports = uploadFile;