Created
June 26, 2020 06:56
-
-
Save readikus/862fe91402398b485fdb070a096a1ae6 to your computer and use it in GitHub Desktop.
Code for uploading an image in nodejs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
The main extra bit you need for this is to use the multer middleware. A middleware is an extra bit you add that just gives additional functionality - i.e. it gives express the ability to handle multi-part forms. | |
Install multer using the npm command and save it to package.json - will let you look that up to make sure you learn it, as you do it all the time :) | |
NPM docs: https://www.npmjs.com/package/multer | |
*/ | |
const express = require('express'); | |
// include the dependancy: | |
const multer = require('multer'); | |
// create the specific uploader, `dest` is the directory where the files are stored. | |
const upload = multer({dest: __dirname + '/uploads/images'}); | |
const app = express(); | |
const PORT = 3000; | |
// like the previous routes, except this time we are specifying it as an HTTP POST handler, and also adding in the middleware which will handle all the file uploading. The param 'photo' relates to the form field's "name" to handle. | |
app.post('/upload', upload.single('photo'), (req, res) => { | |
// req.file will contain some data on the image. More on the npm docs for multer | |
if (req.file) { | |
res.json(req.file); | |
} | |
else throw 'error'; | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Note the enctype - this is the encoding type, that allows the form to take binary files. The form `action` is the URL of your API. | |
Also note the method - that is the HTTP verb (get, post, delete etc.) - these relate to the type of action you want to perform. More info at https://restfulapi.net/http-methods/ (but might be a bit heavy) | |
``` | |
<form action="/upload" method="post" enctype="multipart/form-data"> | |
<input type="file" accept="image/*" name="photo" > | |
<input type="submit" value="upload"> | |
</form> | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment