svnthh
Anime Ending Analyst
LEVEL 1
300 XP
Whether you are building social platform or a simple website, sometimes you need to let users upload their own files. The typical scenario might be: uploading the user's photo for a profile page.
With Node.js and express it is quite easy to create your own file upload service. In this post I will show you how.
In the new folder run `npm init`, and create `package.json` as you usually do for every fresh Node project. Now let's install the dependencies:
npm install --save express multer
multer
is a module that will help us to deal with `multipart/form-data` - a special encoding that browsers are using to transfer files from user's computer to server.
First let's create a tiny application to display an HTML form to a user and also to render the uploaded photos.
Create a new file: main.js and enter the following code:
Now we are ready to make `express` route:
Notice, that inside of route handler we pass request and response objects to `upload()` - a function created by `multer`. This function will parse the request body and enrich `req` object with new data. Finally, there is another callback that is executed once the file is uploaded and saved.
Here's how our app looks now:
Try running it. Select the file and upload it. If you did everything correctly you should see "File has been uploaded" after you submit the form. Let's see what's inside our upload folder. If you open it up, you'll see the file is indeed there, but it has some strange name. 32 meaningless characters without the extension.
This is not a bug, but a feature of multer - this way it makes sure that file names don't clash. If two users upload file called me.jpg, multer will not overwrite one of the files, both will be save.
Most of the time you will want to keep this behavior but sometimes you just want to keep the original file name. Here's how you can do it. We only need to change onUploadDone()
function.
Notice that we used fs - standard node module, to rename the file. Make sure to require()
it in your code. Now the uploaded file will have its original name.
Happy uploading! Here's the code of finished program:
With Node.js and express it is quite easy to create your own file upload service. In this post I will show you how.
In the new folder run `npm init`, and create `package.json` as you usually do for every fresh Node project. Now let's install the dependencies:
npm install --save express multer
multer
is a module that will help us to deal with `multipart/form-data` - a special encoding that browsers are using to transfer files from user's computer to server.
First let's create a tiny application to display an HTML form to a user and also to render the uploaded photos.
Create a new file: main.js and enter the following code:
- const
express =
require(
'express'
)
;
- const
app =
express(
)
;
- app.use
(
express.static
(
`${
__dirname}
/
public`)
)
;
- app.listen
(
3000
,
(
)
=>
{
- console.log
(
'File Uploader is on 0.0.0.0:3000!'
)
;
- }
)
;
- <
javascript>
- This application doesn't do much: it simply serves static files from '
public' folder. Now let'
s create index.html
with an upload form so that our user can pick select a file.
- <
html4strict>
- <!
doctype html>
- <
html lang=
"en"
>
- <
head>
- <
meta charset=
"utf-8"
>
- <
title>
File Upload</
title>
- </
head>
- <
body>
- <
h1>
Upload file</
h1>
- <
form enctype=
"multipart/form-data"
method=
"POST"
action=
"upload"
>
- <
input type=
"file"
name=
"file"
>
- <
button type=
"submit"
>
Upload</
button>
- </
form>
- </
body>
- </
html>
- </
html4strict>
- Start the server and point your browser to http:
//localhost:3000. You should see the form showing up on the screen. Notice that in the HTML code we added few attributes to the form. `enctype="multipart/form-data"` is essenctial for file uploads. `action="upload"` points to the route that will handle the upload. Let's build that route now.
- To do
that we will need a help of little node.js
module called `multer`. It
will de-
code the multipart-
encoded form and reconstruct it as a JSON object on the server side. This
way you will have a quick and easy access to all the submitted fields as well as submitted files.
- First
,
let's initialize `multer`. We will need to tell it where to put uploaded files and what is the name of the submitted form field that contains the file.
- <javascript>
- const uploadPath = `${__dirname}/public/upload`;
- const formFieldName = '
file';
- const upload = multer({dest: uploadPath}).single(formFieldName);
Now we are ready to make `express` route:
- app.post
(
'/upload'
,
(
req,
res)
=>
{
- const
onUploadDone =
(
err)
=>
{
- if
(
err)
{
- console.log
(
err.stack
)
;
- res.send
(
'Could not upload file'
)
;
- return
;
- }
- res.send
(
'File has been uploaded'
)
;
- }
;
- upload(
req,
res,
onUploadDone)
;
- }
)
;
Notice, that inside of route handler we pass request and response objects to `upload()` - a function created by `multer`. This function will parse the request body and enrich `req` object with new data. Finally, there is another callback that is executed once the file is uploaded and saved.
Here's how our app looks now:
- const
express =
require(
'express'
)
;
- const
multer =
require(
'multer'
)
;
- const
app =
express(
)
;
- const
uploadPath =
`${
__dirname}
/
public/
upload`;
- const
formFieldName =
'file'
;
- const
upload =
multer(
{
dest:
uploadPath}
)
.single
(
formFieldName)
;
- app.use
(
express.static
(
`${
__dirname}
/
public`)
)
;
- app.post
(
'/upload'
,
(
req,
res)
=>
{
- const
onUploadDone =
(
err)
=>
{
- if
(
err)
{
- console.log
(
err.stack
)
;
- res.send
(
'Could not upload file'
)
;
- return
;
- }
- res.send
(
'File has been uploaded'
)
;
- }
;
- upload(
req,
res,
onUploadDone)
;
- }
)
;
- app.listen
(
3000
,
(
)
=>
console.log
(
'Listening on 0.0.0.0:3000!'
)
)
;
Try running it. Select the file and upload it. If you did everything correctly you should see "File has been uploaded" after you submit the form. Let's see what's inside our upload folder. If you open it up, you'll see the file is indeed there, but it has some strange name. 32 meaningless characters without the extension.
This is not a bug, but a feature of multer - this way it makes sure that file names don't clash. If two users upload file called me.jpg, multer will not overwrite one of the files, both will be save.
Most of the time you will want to keep this behavior but sometimes you just want to keep the original file name. Here's how you can do it. We only need to change onUploadDone()
function.
- app.post
(
'/upload'
,
(
req,
res)
=>
{
- const
onUploadDone =
(
err)
=>
{
- if
(
err)
{
- console.log
(
err.stack
)
;
- res.send
(
'Could not upload file'
)
;
- return
;
- }
- const
targetPath =
`${
uploadPath}
/
${
req.file
.originalname
}
`;
- fs.rename
(
req.file
.path
,
targetPath,
(
)
=>
{
- res.send
(
'File has been uploaded'
)
;
- }
)
;
- }
;
- upload(
req,
res,
onUploadDone)
;
- }
)
;
Notice that we used fs - standard node module, to rename the file. Make sure to require()
it in your code. Now the uploaded file will have its original name.
Happy uploading! Here's the code of finished program:
- const
fs =
require(
'fs'
)
;
- const
express =
require(
'express'
)
;
- const
multer =
require(
'multer'
)
;
- const
app =
express(
)
;
- const
uploadPath =
`${
__dirname}
/
public/
upload`;
- const
formFieldName =
'file'
;
- const
upload =
multer(
{
dest:
uploadPath}
)
.single
(
formFieldName)
;
- app.use
(
express.static
(
`${
__dirname}
/
public`)
)
;
- app.post
(
'/upload'
,
(
req,
res)
=>
{
- const
onUploadDone =
(
err)
=>
{
- if
(
err)
{
- console.log
(
err.stack
)
;
- res.send
(
'Could not upload file'
)
;
- return
;
- }
- const
targetPath =
`${
uploadPath}
/
${
req.file
.originalname
}
`;
- fs.rename
(
req.file
.path
,
targetPath,
(
)
=>
{
- res.send
(
'File has been uploaded'
)
;
- }
)
;
- }
;
- upload(
req,
res,
onUploadDone)
;
- }
)
;
- app.listen
(
3000
,
(
)
=>
console.log
(
'Listening on 0.0.0.0:3000!'
)
)
;