user7102017
user7102017

Reputation:

Uploading file with express-fileupload

I am trying to upload a file with express-fileupload and am having no luck getting it to work. I can get the file (in this case an image) to 'upload' in the sense that I can get the console to show an image uploaded with the correct folder.

startup.js

router.get('/upload', function(req, res) {
    res.render('upload');
});

router.post('/upload', function(req, res) {
    // The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file 
  let startup_image = req.files.image;

  // Use the mv() method to place the file somewhere on your server 
  startup_image.mv('/images' , function(err) {
      if (err) {
          console.log(err);
      }
  });
});

Then my html form is

<form ref='uploadForm' 
      id='uploadForm' 
      action='/upload' 
      method='post' 
      encType="multipart/form-data">
        <input type="file" name="image" />
        <input type='submit' value='Upload!' />
</form>

Upvotes: 13

Views: 40754

Answers (6)

user8377060
user8377060

Reputation:

You are pointing the directory where the file would go to, but you are not giving it a file name. I would say let the user decide the file name for the client side and add it to the path.

<input name="userFileName" type="text">//userFilename Here</input>
var myFILENAME = req.body.userFilename 
startup_image.mv('/images/'+myFILENAME+'.jpg', ..) //myFILENAME needs to be added here

Also please see Full Example in how to upload files with express-fileupload

UPDATE

I found solution to your problem you need to add __dirname to this line which will let the program know your current directory to your source code.

startup_image.mv(__dirname + '/images' , function(err) {..

UPDATE 2

Here is my source code, if you want you can try it with this.

my html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <form ref='uploadForm' encType="multipart/form-data" class="" action="/upload" method="post">
      <input type="text" name="fileName" value=""><br>
      <input type="file" name="foo" value=""><br>
      <input type="submit" name="" value="upload!">
    </form>
  </body>
</html>

my main source

var express = require("express");
var app = express();
const fileUpload = require('express-fileupload');
//npm install ejs, express, express-fileupload

//middleware
app.use(express.static(__dirname));
app.set('view engine', 'ejs');
app.use(fileUpload());

app.get('/inputFile', function(req, res){
  res.render('inputt');
});

app.post('/upload', function(req, res) {
  // The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
   var startup_image = req.files.foo;
   var fileName = req.body.fileName;
   // Use the mv() method to place the file somewhere on your server
   startup_image.mv(__dirname + '/images/' + fileName + '.jpg' , function(err) {
     if(err){
       console.log(err);
     }else{
    console.log("uploaded");
}
   });
 });

app.listen(7777);

Upvotes: 9

emekaokoli
emekaokoli

Reputation: 165

using async/await style

in your server file do this

const fileUpload = require('express-fileupload');

 app.use(
  fileUpload({
    limits: { fileSize: 50 * 1024 * 1024 },
    useTempFiles: true,
   // dir for windows PC
    tempFileDir: path.join(__dirname, './tmp'),
  }),
);

then in your controllers, do this

  const file = req.files.filename;
  await file.mv(file.name);

  if (!file || Object.keys(req.files).length === 0) {
    return res.status(400).console.error('No files were uploaded.');
  }

Upvotes: 2

Ahsan Khan
Ahsan Khan

Reputation: 361

this way file.mv(path.resolve(__dirname, '../public/images', filename)

Upvotes: 0

//install path module 
const path = require('path');

 // remaining code

let startup_image = req.files.image;

startup_image.mv(path.resolve(__dirname,'/images',startup_image.name), function(error){
  //remaining code
})

Upvotes: 0

Thức Trần
Thức Trần

Reputation: 137

You have to create folder images!

Upvotes: 0

Michael Nelles
Michael Nelles

Reputation: 5992

This solution is for non ejs and exporting modules solution:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>File Upload</title>
  </head>
  <body>
    <form ref='uploadForm' encType="multipart/form-data" class="" action="/path/to/nodejs/upload/file" method="post">
      <input type="file" name="my_file"><br>
      <input type="submit" name="" value="upload">
    </form>
  </body>
</html>

Now here is the NodeJS

const express = require("express");
const app = express();
const fileUpload = require('express-fileupload');

app.use(fileUpload({ safeFileNames: true, preserveExtension: true }))

app.post('/', function(req, res) {
    // The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
    let the_file = req.files.my_file;

    the_file.mv('/path/to/html/uploads/up/' + the_file.name , function(err) {

        res.writeHead(200, {"Content-Type": "text/plain"});
        if(err){
            console.log(err);
            res.write(err);
            res.end();
        } else {
            console.log("uploaded");
            res.write("upload of file "+the_file.name+" complete");
            res.end();
        } 

   });

});

module.exports = app;

Upvotes: 1

Related Questions