ref – https://dzone.com/articles/upload-files-or-images-to-server-using-nodejs
client side
Server side – index.js
Make sure you create the folder Images at the the directory your index.js is at.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
var express = require('express') var app = express() var port = process.env.PORT || 8080 var multer = require('multer'); var bodyParser = require('body-parser'); app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS'); next(); }); // bodyParser app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); // image storage var Storage = multer.diskStorage({ destination: function(req, file, callback) { callback(null, "./Images"); }, filename: function(req, file, callback) { console.log("---The file name is---"); console.log(file.fieldname); console.log("---The original name is---"); console.log(file.originalname); callback(null, file.fieldname + "_" + Date.now() + "_" + file.originalname); } }); // multier takes the requst object var upload = multer({ storage: Storage }).array("imgUploader", 1); //Field name and max count console.log("index.js - file upload ready at http://localhost:8080/api/Upload for POST requests"); app.post("/api/Upload", function(req, res) { console.log("POST request on api/Upload, you are trying to upload an image"); upload(req, res, function(err) { if (err) { console.log("----error uploading file----"); console.log(err); return res.end("Something went wrong!"); } return res.end("File uploaded sucessfully!."); }); }); app.listen(port); console.log(' pictorial list RESTful API server on: ' + port); |
However, our solution always jumps to another page.
In order to do it without any jump, we do it without a form
non-form way
First, we create a file uploader, and button control
1 2 |
<input type="file" name="imgUploader" id="imgUploader" /> <button name="submit" id="btnSubmit" onclick="uploadImage()">upload image</button> |
For the button, whenever we press it, we will run function uploadImage
In this function, we first get the file object via the files property. The files property is an array, and we simply get the first element.
Once we have this file, we create a FormData object, append our file to it. Make sure to call it “imgUploader” as that’s what our multer code from the server side is expecting.
Assign the form data object to body and that’s it.
1 2 3 4 5 6 7 8 9 10 11 |
function uploadImage() { var image = document.getElementById("imgUploader").files[0]; console.dir(image); var formData = new FormData(); formData.append('imgUploader', image); fetch('http://localhost:8080/api/Upload', { method:'POST', body: formData }); } |