Uploading file with express-fileupload Uploading file with express-fileupload express express

Uploading file with express-fileupload


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//middlewareapp.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);


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.');  }


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;