I need to upload a image(jpg||png||jpeg) to the server I created with node js.
I have the router and the requestHandlers.. that redirect to this function:
function reqUpload(request, response) {
var form = new formidable.IncomingForm();
form.parse(request, function (error, fields, files) {
lastFileUploaded=files.up.originalFilename;
if (files.up.originalFilename.match(/.(jpg|jpeg|png)$/i)) {
//check if alredy exists
fs.access(files.up.originalFilename, fs.F_OK, (err) => {
if (err) {
fs.rename(files.up.filepath, files.up.originalFilename, function (err) {
if (err) {
fs.unlink(files.up.originalFilename);
fs.rename(files.up.filepath, files.up.originalFilename);
}
var data;
fs.readFile('./html/std.html', 'utf8', function (err, data) {
if (err) {
console.error(err);
return
}
response.writeHead(200, { "Content-Type": "text/html" });
response.write(data);
response.end();
});
})
}else{
console.log("Already exists, replacing it!");
fs.rename(files.up.filepath, files.up.originalFilename, function (err) {
if (err) {
fs.unlink(files.up.originalFilename);
fs.rename(files.up.filepath, files.up.originalFilename);
}
})}
});
} else {
console.log("format not accepted! try again.");
}
This is working if I upload my file via a button and the form action =”/reqUpload”
however, I need to load in the same page.
How do I do it with ajax + jquery?
I need to display the image uploaded in the same page I uploaded it, without refreshing the page.