I'm able to upload images to my server then to the Postgresql database. I'd like to view an image on the browser by inputting the url like "http://localhost:5000/photoURL/photoURL_1665529814000.jpg" but nothing is displayed. Below is my code
const storage = multer.diskStorage({
destination: "./photoURL", /*(req, file,cb) => {
cb(null, __dirname '/images/')
},*/
filename: (req, file, cb) => {
console.log(file);
return cb(null,`${file.fieldname}_${Date.now()}${path.extname(file.originalname)}`);
}})
const upload = multer({storage: storage });
router.use('/photoURL',express.static('photoURL'));
router.use(cors());
router.use(express.json());
router.use(body_parser.urlencoded({extended: true}));
//add doctor to database
router.post('/',upload.single('photoURL'), (req, res, next)=> {
//const myid = seconds;
const username = req.body.username;
const password = req.body.password;
const contact = req.body.contact;
const speciality = req.body.speciality;
const photoURL = `http://localhost:5000/photoURL/${req.file.filename}`;
const sqlInsert = 'INSERT INTO doctors (username, password, contact, speciality, photourl) VALUES ($1, $2, $3, $4, $5);';
pool.query(sqlInsert,[ username,password, contact, speciality, photoURL, ], (error, results) =>{
if (error) {
throw error
}
res.status(200).json({
message: "Successful insertion to database",
username: username,
password: password,
contact: contact,
speciality: speciality,
photoURL: photoURL
})
// res.send(results.rows);
console.log(results.rows);
});
});
CodePudding user response:
destination for multer.diskStorage is a function, not a string. So your, storage will look like this
import path from 'path'
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, path.join(__dirname, './')) /* Will store in current directory*/
},
filename: (req, file, cb) => {
console.log(file);
return cb(null,`${file.fieldname}_${Date.now()}${path.extname(file.originalname)}`);
}})
To access your file, use app.use() middleware in index file
app.use(
'/photoUrl',
express.static(path.join(__dirname, './yourstoredfilepath'))
);