Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ERROR UPLOADING FILE using the javascript and I also use multer in handling the fileupload #1224

Open
barbiedo opened this issue Aug 29, 2023 · 5 comments

Comments

@barbiedo
Copy link

what are the error of my code ?

"this is the upload photo code

const express = require('express');
const multer = require('multer');
const path = require('path');
const { DB_CURRENT_TIMESTAMP, queryDb } = require('@api/utils/mysql');

//const app = express();
//const port = process.env.SERVER_PORT || 3000;
const router = express.Router();

// Set up storage for uploaded files
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '../assets/uploads');
},
filename: function (req, file, cb) {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
const fileExtension = path.extname(file.originalname);
cb(null, file.fieldname + '-' + uniqueSuffix + fileExtension);
}
});

const upload = multer({ storage: storage });

// Serve uploaded files statically
//app.use('/uploads', express.static('uploads'));
router.use('/uploads', express.static('uploads'));

// Handle file upload
router.post('/api/upload-photo', upload.single('image'), async (req, res) => {
if (!req.file) {
return res.status(400).json({ message: 'No file uploaded' });
}

// You can perform additional logic here, like saving the file path to a database
// and returning a response.

try {
	const { image = '' } = req.body;

	if (!image) {
		return res.status(400).json({
			message: 'Please select an Image.',
    	});
	}

	const imagePath = `/uploads/${req.file.filename}`; // Update the path to match your file storage location

	// Save file path to the database
	await queryDb(`
		INSERT INTO gallery (date_uploaded, image) VALUES (?, ?)`,
		[DB_CURRENT_TIMESTAMP, imagePath]
	);

	return res.status(200).json({
		message: 'Image Uploaded!'
	});
	
} catch (err) {
	res.status(500).json({
		message: `Server error : ${err.message}`
	});
}

res.status(200).json({ message: 'Image Uploaded' });
});

// app.listen(port, () => {
// console.log(Server is running on port ${port});
// });
module.exports = router;

and these are the "get gallery data" code

//get all gallery

const { queryDb } = require('@api/utils/mysql');

module.exports = async function(req, res) {
try {
var {

    } = req.body;

    message= '';

    var gallery = await queryDb('SELECT * FROM gallery');
    
    return res.status(200).json ({
        gallery
    });
}
catch(err) {
    // console.log(err.message);
    res.status(500).json({
        message: `Server error : ${err.message}`
    });
}

}

@barbiedo barbiedo changed the title ERROR UPLOADING FILE ERROR UPLOADING FILE using the javascript and I also use multer in handling the fileupload Aug 29, 2023
@Doc999tor
Copy link

You didn't attach the specific error you got, but as far as I can see:

  1. the row const { image = '' } = req.body; and returning 400 might be not necessary
  2. since you already handle the image field in the request by the if (!req.file) {
  3. Middleware upload.single('image') will take the image field from the body and populate the req.file

@barbiedo
Copy link
Author

This is the error of my code, i don’t know what is the wrong of code.

IMG_9989

@barbiedo
Copy link
Author

IMG_9985

@jha-adrs
Copy link

jha-adrs commented Sep 1, 2023

I am having a error too, I dont understand what I am doing wrong

Error:
Error: ENOENT: no such file or directory, open 'C:\Users.......src\routes\uploads\product_file-1693576521663.xlsx'

const path = require('path');
const multer = require('multer');
let storage = multer.diskStorage({
destination: function (req, file, cb) {
// Create the uploads folder if it does not exist
if (!fs.existsSync('./uploads')) {
fs.mkdirSync('./uploads');
}
cb(null, './uploads/');
},
filename: function (req, file, cb) {
let datetimestamp = Date.now();
cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length - 1]);
}
});
const upload2 = multer({
storage: storage,
});
const upload = multer();

routes.post('/product-file-upload',upload2.single('product_file'),require('../controllers/products/updateSwagProducts'));
//routes.post('/product-file-upload',upload.single('product_file'),require('../controllers/products/updateSwagProducts'));

The file contents are coming through the request but I somehow cant save it, even though I have created the uploads folder

@joeyguerra
Copy link

Post the html that you're using.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants