Note: Despite coming across this post, I couldn't find it helpful. Other related posts were focused on angular/react, which are not relevant to my current project.
I have implemented a file upload feature that should provide a response indicating whether the uploaded file is of the correct type. While the file upload functionality works as intended, the issue arises when the page automatically redirects to the file's location. My goal is to keep the page on the same location after the file is uploaded.
home.ejs:
<!-- upload video -->
<form method="post" action="/upload" class="custom-file" enctype="multipart/form-data">
<input type="file" name="video-file" class="custom-file-input" />
<span class="custom-file-control"></span>
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle"
type="button"
id="dropdownMenuButton"
data-toggle="dropdown"
aria-haspopup="true"
aria-expanded="false"
name="number-of-cores">
Use all Cores
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item">Use all Cores</a>
<a class="dropdown-item">Use one Core</a>
</div>
</div>
<input class="btn btn-primary upload-btn" type="submit" id="upload-btn" value="Upload">
The reason for avoiding page redirection is to display whether the uploaded file format is correct or not directly on the same page without any interference.
$('body').on('click', '#upload-btn', function (event) {
$.ajax({
type: 'POST',
url: '/',
dataType : "application/json; charset=utf-8",
contentType: JSON.stringify(false),
success: function (response) {
$("#errorMessage").html("* file successfully opened");
console.log('successfully uploaded', response);
},
error: function (result) {
$("#errorMessage").html("* Incorrect file/no file given");
console.log('couldn\'t upload');
}
});
//return false;
})
server.js
const express = require('express');
const multer = require('multer');
var path = require('path')
const app = express();
app.set('view engine', 'ejs');
app.set('views', './views');
app.use(express.static('public'));
function fileFilter (req, file, cb) {
if (path.extname(file.originalname) !== '.mp4') {
return cb(null, false);
}
cb(null, true);
}
const upload = multer({ dest: 'uploads/', fileFilter:fileFilter});
app.get('/', (req, res) => {
res.render('home', { testGreeting: 'Hello world' });
});
app.post('/upload', upload.single('video-file'), function(req, res) {
console.log(req.file);
console.log(req.params);
if (req.file) {
console.log("successfully received");
res.send({success: "success"});
}
return res.end();
});
app.listen(3000, () => console.log('Listening on Port 3000.'));
On a side note, my ajax code consistently triggers the error block and never the success block. Any assistance with this would be highly appreciated. Thanks!
UPDATE: event.preventDefault()
was the solution:
$('body').on('click', '#upload-btn', function (event) {
event.preventDefault();
$.ajax({
... //same as before
});
return false;
})