My users want to be able to upload their files using drag and drop. So I downloaded dropzone.js and everything works fine except for one thing.
When I submit the form, I receive the error message "Image is required" although I did upload an image.
I started debugging and added a few console.logs. That only got me even more confused.
This is what was printed to the console:
DROPPED FILE:[object Object]
WE GOT HERE!
POST /upload 302 95.430 ms - 0
GET /upload 200 5.887 ms - 6952
DROPPED FILE:undefined
POST /upload 302 3.685 ms - 100
GET /upload 200 3.795 ms - 6930
Apparently, the page is loaded twice ? This makes no sense and I do not understand what is causing this. It seems the image is passed the first time though.
What is going on ?
FRONT:
<form enctype="multipart/form-data" method="post" action="/upload" class="uploadForm dropzone" id="my-awesome-dropzone">
<div class="form-group">
<label>Title</label>
<input type="text" class="form-control" name="title" placeholder="A catchy title !" required maxlength="30" minlength="2">
</div>
<div class="form-group">
<label>Section</label>
<select name="section" class="form-control">
<option value=""></option>
<option value="Screenshots">Screenshots</option>
</select>
</div>
<label>
<br> File too large ? Try <a href="http://compressimage.toolur.com/" target="_blank">CompressorImage</a> or <a href="https://tinyjpg.com/" target="_blank">TinyPNG</a></label>
<div class="dz-message" data-dz-message><span class="uploadZone">Image (Max: 2MB)<br>Drop your Image Here or Click</span></div>
<div class="form-group">
<label>Game</label>
<input type="text" class="form-control" name="game" placeholder="Name of the Game related to your Art if applicable" maxlength="30">
</div>
<div class="g-recaptcha" data-sitekey="...."></div>
<div class="marginTop">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
<script src="../public/js/dropzone.js"></script>
<script>
Dropzone.options.myAwesomeDropzone = {
paramName: "image",
acceptedFiles: 'image/*',
maxFilesize: 2, // MB
accept: function (file, done) {
console.log("uploaded");
done();
},
init: function () {
this.on("addedfile", function () {
if (this.files[1] != null) {
this.removeFile(this.files[0]);
}
});
}
};
</script>
BACK:
var upload = multer({dest:"./public/images/uploads/", limits: {fileSize: 2100000},
fileFilter: function (req, file, cb) {
var filetypes = /jpeg|jpg|png/;
var mimetype = filetypes.test(file.mimetype);
var extname = filetypes.test(path.extname(file.originalname).toLowerCase());
if (mimetype && extname) {
return cb(null, true);
}
cb("Error: File upload only supports the following filetypes - " + filetypes);
}
}).single("image");
router.post("/", function(req, res, next){
upload(req,res, function (err) {
const uid = "...";
if (err) {
req.flash("error_msg", "Upload failed. Please try again. Info: Maximum file size is 2MB in case your file is too large.");
res.redirect("upload");
return
}
var title = req.body.title;
var section = req.body.section;
console.log("DROPPED FILE:"+ req.file);
req.checkBody('title', 'Title is required').notEmpty();
req.checkBody('title', 'Title is too long, max: 30 charachters !').len(2,30);
req.checkBody('game', 'Game Name is too long, max: 30 charachters !').len(0,30);
req.checkBody('section', 'Section is required').notEmpty();
var errors = req.validationErrors();
if(errors){
res.render('upload', {
errors: errors
});
}
else {
if (req.file){
console.log("WE GOT HERE!")
verifyRecaptcha(req.body["g-recaptcha-response"], function(success) {
if (success) {
var now = global.serverTime;
var userRef = admin.database().ref("users/"+uid);
userRef.once("value", function(user){
var userData = user.val();
console.log("FILE NAME:"+req.file.filename);
var image = req.file.filename;
var section = req.body.section.toLowerCase();
bucket.upload("./public/images/uploads/"+req.file.filename, function(err, file) {
if (!err) {
fs.unlink("./public/images/uploads/"+req.file.filename, (err) => {
if (err) {
} else {
}
});
var IDref = admin.database().ref("posts/"+section+"/lastID");
IDref.once("value", function(IDsnapshot){
var number = IDsnapshot.val();
var postRef = admin.database().ref("posts/"+section).push();
var UID = postRef.key;
if(req.body.game != "" && req.body.game != null && req.body.game != undefined) {
var post = {
title: req.body.title,
section: req.body.section,
game: req.body.game,
image: image,
author: uid,
username: userData.username,
section: section,
upvotes: 0,
downvotes: 0,
inversedScore: 0,
inversedtimestamp: -now,
id: number - 1,
key: UID,
hot: false
}
}
else {
var post = {
title: req.body.title,
section: req.body.section,
image: image,
author: uid,
username: userData.username,
section: section,
upvotes: 0,
downvotes: 0,
inversedScore: 0,
inversedtimestamp: -now,
id: number - 1,
key: UID,
hot: false
}
}
IDref.set(post.id);
postRef.set(post);
var authoredPost = {
image: image,
title: req.body.title,
inversedtimestamp: -now,
section: section
}
var userRef = admin.database().ref("users/"+uid+"/posts/"+UID.toString());
userRef.set(authoredPost);
userTimeRef = admin.database().ref("users/"+uid+"/timestamp");
var timestamp = global.serverTime;
userTimeRef.set(timestamp);
});
req.flash("success_msg", "Post Created. Reload page.");
res.redirect(section+"/index");
}
else {
fs.unlink("./public/images/uploads/"+req.file.filename, (err) => {
if (err) {
} else {
}
});
req.flash("error_msg", "Failed to Upload"+err);
res.redirect(req.get('referer'));
}
});
});
} else {
req.flash('error_msg', 'Recaptcha failed. Try again.');
res.redirect('upload');
}
});
}
else {
req.flash("error_msg", "Image is required");
res.redirect(req.get('referer'));
}
}
})
});
via TheProgrammer
No comments:
Post a Comment