Uploading Files using Node JS

3k views Asked by At

I am trying to upload js or txt files to my local directory using Node JS. I know there are many tutorials out there. I watched a tutorial on youtube that uses following code:

index.html

  <html xmlns="http://www.w3.org/1999/xhtml">
  <head>
  <meta charset="utf-8" />
   <title>Upload images to server using Node JS</title>

  </head>
  <form method="post" enctype="multipart/form-data" action="/">
    <input type="file" name="filename">
    <input type="submit" value="upload">
  </form>

app.js

var express = require('express'),
app = express(),
http = require("http").Server(app).listen(8000),
upload = require("express-fileupload")

app.use(upload())


 console.log("Listening to port 8000");
 app.get("/",function(req,res){
  res.sendFile(__dirname+"/index.html");
 })

 app.post("/", function(req,res){
    if(req.file){
    var file = req.files.filename,
        filename = file.name;
    file.mv("./upload/"+filename,function(err){
        if(err){
            console.log(err);
            res.send("err occurd");
        }
        else
        {
            res.send("done");
        }
    })
  }
})

This code works when the guy in the video explains it. However, when I am trying to upload a file it does not upload anything. It even does not show any error. So I am not sure what is happening!

Any suggestion?

1

There are 1 answers

1
Bsalex On

I believe you've missed the files field name

if(req.file){

should be

if(req.files){