Multer: File not uploading but multer not giving me any errors

Created on 22 Sep 2016  路  74Comments  路  Source: expressjs/multer

I am trying to upload a file. The file does not get uploaded but multer does not give me any errors.

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    console.log("Hello people in storage");
    return cb(null, 'client/assets/uploads');
  },
  filename: function (req, file, cb) {
    var ext = file.mimetype.split('/')[1];
    return cb(null, Hello + '-' + Date.now() + "." + ext);
  }
})

In fact, it does not even go to the console.log line. Can you help me please?

Most helpful comment

It took complete one night for me to resolve. It was conflicting with another package require('express-fileupload');
Uninstalled it. And multer worked fine as expected.

All 74 comments

How are you using storage?

var upload = multer({ storage: storage, limits: {fileSize: 1000000}}); router.post('/upload', upload.single('file'), controller.create);

This same code works in another of my project. Maybe some other modules are messing up with this?

hi, I am also facing the same problem.... if u got the solution then plz share with me.. I already wasted my 3 days in this problem.

thanks

@SHAPPY0 , I started a new project and it works fine in that.

But I can't change project... If you get any solution then let me know.. Please.

I'm having a similar issue. I get no errors when uploading but the file never uploads. Don't know where it is. I'm using a basic example

var multer = require('multer'); var upload = multer({dest: 'public/uploads'});

router.post('/testimage', upload.single('myImage'), function(req, res, next) { if (req.file) { console.dir(req.file); return res.end('Thank you for the file'); } res.end('Missing file'); });

I see the Thank you message with no errors but when I look in the directory (public/uploads) there's nothing there.

I'm running nginx so that's my issue.

I'm having this same issue, but my req.file and req.body objects are both undefined

Hi @grantlyk,

Are u using angular.js at the front end????

@SHAPPY0 No i'm not however I have done so in the past with multer, I was literally just about to post here again saying i've resolved my issue. my problem is that I was using postman to test my API endpoint and it was specifying the content type application/json rather than multipart/form-data

Are you still having your issue?

@Grantlyk,
No , i also solved my issue.... I was using angular.js so I had need to send file from front to back end using angular.js
I found a solution and solved it.

Cheers

Facing same problem here.. No error and doesn't work. Every time it just creates empty folder.
Can somebody please help.

```
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/')
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
})

var uploading = multer({storage: storage}).single('file');

module.exports = function (router) {
router.route("/upload").post(uploading, function (req, res, next) {
uploading(req, res, function (err) {
if (err) {
console.log(err);
}
res.send('Successfully uploaded ' + req.files.length + ' files!');
})

});

};```

Facing same problem here:

I'm using on backend:

Multer: 1.3.0
Express and Express router

And in frontend:

Angular 4.1.3 with ng2-file-upload 1.2.1

Relevant code of backend

var express     = require("express"),
                app             = express(),
                cors            = require('cors'),
                bodyParser      = require("body-parser"),
                methodOverride  = require("method-override"),
                http            = require("http"),
                multer          = require('multer');
                server          = http.createServer(app),
                router          = express.Router()
                    .....
                    app.use(function (req, res, next) {
                    res.header("Access-Control-Allow-Methods", "POST, PUT, OPTIONS, DELETE, GET");
                    res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
                    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
                    res.header("Access-Control-Allow-Credentials", true);
                    next();
                });


    var storage = multer.diskStorage({
        destination: function (req, file, cb) {
            cb(null, './uploads/')
        },
        filename: function (req, file, cb) {
            console.log("aha " + file.originalname);
            cb(null, file.originalname)
        }
    })


    var upload = multer().single('file')

    //**THIS IS MANDATORY, WITHOUT THIS NOT WORK**
    app.use(multer({
     storage:storage
     }).single('file'));


              app.use(bodyParser.urlencoded({extended: false}));
              app.use(bodyParser.json());
              app.use(cors());
              app.use(methodOverride());
              app.use(passport.initialize());
              app.use(busboyBodyParser());
              //
              app.use('/api', router);


router.post("/uploadPhoto", function(req, res) {
    console.log(req.file);
    upload(req,res,function(err){
        if(err){
            res.status(500).json({'success':false});
            return;
        }
        res.status(200).json({'success':true});
    });
});

And this is relevant part of Frontend

upload.html

....
  <input name="file" type="file" ng2FileSelect [uploader]="uploader"/>

<button type="button" class="btn btn-success btn-xs"
                                    (click)="item.upload()" [disabled]="item.isReady || item.isUploading || item.isSuccess">
                                <span class="glyphicon glyphicon-upload"></span> upload
                            </button>
.....

upload.ts

import { FileUploader } from 'ng2-file-upload';
...

public uploader:FileUploader;
constructor() {

        this.uploader  = new FileUploader({url: this.URL + "uploadPhoto", itemAlias: 'file'});

        this.uploader.onBeforeUploadItem = (item) => {
            item.withCredentials = false;
        }

        this.uploader.onCompleteItem = (item:any, response:any, status:any, headers:any) => {
            console.log("ImageUpload:uploaded:", item, status, response);
        };

    }

app.module

import { FileSelectDirective, FileDropDirective } from 'ng2-file-upload';
....
declarations:[FileSelectDirective,.....

Any idea, or someone solved the problem?

Might be a better idea to post your front end code, chances are it's the wrong content type

You 're right Grantlyk, I've updated my original message with more info of frontend and backend

Dear Guys I had same problem and I resolved by just replacing the path of uploads
cb(null, 'uploads/') wrong
cb(null, './uploads/') correct

so I got my file uploaded

Hi Guys
Faceing same issue while uploading without error works prefectly in local but not nignx server thank u
@dadixon have you fixed issue

Use "Accept": "application/json".

Remove "Application-Type": "application/json"

It will work

Hi Guys
Faceing same issue while uploading without error works prefectly in local but not server @dadixon have you fixed issue

i am using multer to upload files it is working perfectly on local machine but when service is hosted on cloud server and file is uploaded from local machine the multer is creating a file with the file name with size 0 kb can anbody tell me what i am doing wrong?

my front end is C# windows application.

Guys, I was having the same problem - "No errors, but file does not upload".
I found that I forgot adding enctype attribute equalling to "multipart/form-data".
Though I didn't find any information about html code on multer description, your html should look something like:
<form class="" enctype="multipart/form-data" action="/imageUploader/loggedIn" method="post"> <input type="file" name="photo" value="" /> <button type="submit" name="button">Submit</button> </form>

file will be upload in your root folder path.

/home/username/project-folder/static/upload
instead of this path it will in
/home/username/static/upload

check it

I also had this kind of issue. It didn't even give me any errors and everything seemed okay, however multer didn't save my images. You probably face this problem because of routing. I had server.js file and its route index.js in another folder. I thought that i had to set a destination according to location of index.js, but you should set a destination according to where your main server is located! Hope it will help you!

2 things

  1. Make sure the folder you're trying to save to is already created. Node will not create it for you if it does not exists. if you're using storage. (It will, if you're using dest, but no renaming then)
  2. As @Sunjay10it29 pointed out Make sure the folder name is
    cb(null, './uploads/') instead of cb(null, 'uploads/')

just need resolve the path, try this.

const storage = multer.diskStorage({

  destination: function (req, file, cb) {
    cb(null, path.resolve(__dirname, './test'))
  },

  filename: function (req, file, cb) {
    cb(null, file.originalname)
  }
})

whit <3 Cesar.

Hi all,

For me, the folder was created "uploads" and I got File object in req.files.file, but file is not saved into uploads folder and File path is "/var/folders/82/3s2yq3zj77l3xn1xvy9pgfx40000gn/T/upload_6bcd336e42b32122a8ed682e52ab".
I use restify.

const upload = multer({dest: 'uploads/'})

server.post({ path: "photo", version }, upload.single('file'), this.savePhoto.bind(this))

savePhoto(req, res, next) {
    console.log('FILE: ', req.files.file)

    res.json(200, {})
    return next()
}

@shystruk you probably want to look at req.file, instead of req.files.file 馃憤

@LinusU

console.log('FILE: ', req.file) => undefined

this issue is not yet solved...pls guys am also having the same problem here...
i wanna be able to post images without using the front end(Angular)

@danndav
I did it in a native way. Works fine for one file. I use AWS S3 bucket for saving files.

fs.readFile(req.files.file.path, (err, fileData) => {
 // => fileData [Buffer]          
})
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, path.resolve(__dirname, './uploads'))
  },
  filename: function (req, file, cb) {
    cb(null, file.originalname)
  }
})

not working for me

It took complete one night for me to resolve. It was conflicting with another package require('express-fileupload');
Uninstalled it. And multer worked fine as expected.

Hi,
I got same issue.
I used postman to send request.
Here my code: https://paste.ofcode.org/QQj9gG3HACVsbkqmsqQwzE
I tried all suggestion above but it still not working.
If i use var upload = multer({ dest: 'uploads/' }), it work.
Any idea for this?

Same problem. Removing the filename, storage passed inside multer works... But i need the filename

const storage = multer.diskStorage({

destrination: function(req, file, cb) {
    cb(null, path.resolve(__dirname, './uploads/'));
},
filename: function(req, file, cb) {
    cb(null, new Date().toISOString() + file.originalname);
}

});

const upload = multer({ storage: storage });

it's not work for me..

after this i get path

path: '/tmp/2018-05-27T18:18:45.184ZScreenshot from 2018-05-17 10-26-39.png',

through i want to store image or file in uploads folder.

Hello everyone, I also had this issue:

const storage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, './uploads/');
    },
    filename: function(req, file, cb) {
        cb(null, new Date().toISOString() + file.originalname);
    }
});

BUG(postman):

{
    "error": {
        "message": "ENOENT: no such file or directory, open 'C:\\Users\\angutierrez\\Pictures\\grid_data\\uploads\\2018-05-28T20:25:00.945Zdescarga.jpg'"
    }
}

and I resolved by deleting "new Date().toISOString() +":

const storage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, './uploads/');
    },
    filename: function(req, file, cb) {
        cb(null, file.originalname);
    }
});

It works for me.

solved: I forgot:
enctype="multipart/form-data"
in my HTML form.

in windows server I also had this problem. Change filename callback function

 cb(null, new Date().toISOString() + file.originalname);

to

```javascript
cb(null, new Date().toISOString().replace(/[-T:.Z]/g, "") + file.originalname);
````
I think this problem happens because of windows not allowed ':' in filename.

the same issue here. It would be helpful at least to add some check(s), so it'll be less confusing and more transparent.
I need to upload files in 2 different destinations, therefore, I create 2 upload objects:

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, path.join(root, 'dest1'));
    },
    filename: (req, file, cb) => {
        const newFilename = file.originalname;
        cb(null, newFilename);
    },
});
global.upload = multer({ storage });

const storage_2 = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, path.join(root, 'dest2'));
    },
    filename: (req, file, cb) => {
        const newFilename = file.originalname;
        cb(null, newFilename);
    },
});
global.upload2 = multer({ storage_2 });    

But when I look what I actually got, I see:
upload:

Multer {
  storage: 
   DiskStorage {
     getFilename: [Function: filename],
     getDestination: [Function: destination] },
  limits: undefined,
  preservePath: undefined,
  fileFilter: [Function: allowAll] }

upload2:

Multer {
  storage: MemoryStorage {},
  limits: undefined,
  preservePath: undefined,
  fileFilter: [Function: allowAll] }

solution (be explicit in the upload object ):

global.upload2 = multer({
  storage: multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, path.join(root, 'dest2'));
    },
    filename: (req, file, cb) => {
        const newFilename = file.originalname;
        cb(null, newFilename);
    },
  })
});

Are there other packages that multer is known to conflict with? I am using multer on one route and it doesn't seem to be doing anything at all. I am just trying to parse a text file, but req.file and req.files are both undefined?

@AdamT213 it will conflict with anything that reads the body-stream before it has been passed to multer... Which middlewares are you using?

Guys if you face such error, kindly check the content type set from front end/ postman before making a request.

I think this problem happens because of windows not allowed ':' in filename.

yeah you right!

same problem here, and I copied examples from the web. I assure that the name of my file to upload is the same as what is passed to the upload function. Nothing happend, no error but no file is saved. The folder is also not created.

var express = require('express');
let crypto = require('crypto');
var router = express.Router();
let multer = require('multer');
let fs = require('fs-extra');

let upload = multer({
storage: multer.diskStorage({
destination: (req, file, callback) => {
let path = ./uploads/ + crypto.randomBytes(12);
fs.mkdirsSync(path);
callback(null, path);
},
filename: (req, file, callback) => {
//originalname is the uploaded file's name with extn
callback(null, file.originalname);
}
})
});
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('main');
});

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

router.post('/twoFacesMorphingRes', upload.single('img1'),
function(req, res, next) {
res.render('twoFacesMorphingRes');
});

I had a very similar issue: was that apparently it is not recognised as a file by Multer if there is no .csv as key (extension file):

https://stackoverflow.com/questions/31734164/how-do-i-send-a-file-from-postman-to-node-js-with-multer

hope it helps,

delete it module

Upload works fine in my local server, exact same code does not work on company server. Upload returns no error but no file uploads. Does anyone want to hazard a guess what environment might cause this?

It took complete one night for me to resolve. It was conflicting with another package require('express-fileupload');
Uninstalled it. And multer worked fine as expected.

wow, you are awesome! my project had the same issue and it's reason just match your explain!

To anyone having issues configuring multer to work with other express middlewares, check out this blog post I wrote on the topic, you might find it useful.

I also got stuck on this. The big gotcha was that the more trivial initialization of the uploader uses "dest" as a key whereas the object initialization (where you can set the filename to be not random) uses "destination" as a key.

multer({dest: './uploads/'});

versus

const uploadStorageConfig = multer.diskStorage({
  destination: './uploads/',
  filename: (req, file, callback) => {
    callback(null, file.originalname);
  },
});

"Whoops! That unsubscribe link isn't valid for your account."
Unsubscribe, please

Hi,
I got same issue.
I used postman to send request.
Here my code: https://paste.ofcode.org/QQj9gG3HACVsbkqmsqQwzE
I tried all suggestion above but it still not working.
If i use var upload = multer({ dest: 'uploads/' }), it work.
Any idea for this?

I am also using PostMan for sending requests and using the code snippt you mentioned is working..
failed in my case

in windows server I also had this problem. Change filename callback function

 cb(null, new Date().toISOString() + file.originalname);

to

cb(null, new Date().toISOString().replace(/[-T:\.Z]/g, "") + file.originalname);

I think this problem happens because of windows not allowed ':' in filename.

thank you!!! this is really working :)

unsubscribe

I am facing the same issue, not able to upload image using multer.

Try using Busboy instead of Multer to upload any file. Refer this article for more info. It is working fine.

`

enctype = "multipart/form-data"
action = "/api/photo"
method = "post"

`
without the multipart/form-data, file will not be uploaded.

I had a similar problem, no errors, no file uploaded, found out it was the cache with the angular service worker that was causing the issue. If I disable the cache it just works, wonder if there's a solution for this.

I'm running nginx so that's my issue.

Thanks so much @dadixon for the nginx mention; I was going a bit crazy there trying to figure out the source of the error.

For anyone else using nginx and not getting an error, you can update your nginx config:

sudo nano /etc/nginx/nginx.conf

Then under the http { (assuming you are using http; mine is an ec2 connected to a load balancer for https):

add the line
client_max_body_size 8M; or whatever you want the limit to be.

So end result is

http { client_max_body_size 8M; ... other stuff }
then reload nginx, which varies depending on your server type.

Uninstalled it. And multer worked fine as expected.

Thanks, I apply the way as you suggested and it works now.

If you are using multer in a Google Cloud Function. Check workaround on stackoverflow

PLEASE STOP SPAMMING ME

and fix the bug: "Whoops! That unsubscribe link isn't valid for your account."

@plmnjo you can click those unsubs button on the issue man :rofl:

I did this config and worked fine:

import multer from 'multer';
import crypto from 'crypto';
import { extname, resolve } from 'path';

const multerConfig = {
  storage: multer.diskStorage({
    destination: resolve(__dirname, '..', '..', 'tmp', 'uploads'),
    filename: (req, file, cb) => {
      crypto.randomBytes(16, (err, res) => {
        if (err) {
          return cb(err);
        }

        return cb(null, res.toString('hex') + extname(file.originalname));
      });
    },
  }),
};

export default multerConfig;

Note: The originalname word need to be lowercase.

I found the issue to be that Windows was uploading CSV files with content type application/octet-stream (inside of multipart/form-data), where as OS X was using text/csv as expected.

This discrepancy led multer to discard the file, but it did so without erroring. It simply didn't set req.file (using memory storage).

The fix was to modify the file type prior to sending in AngularJS as follows:

if (file.type !== 'text/csv') {
  file = file.slice(0, file.size, 'text/csv');
}

in windows server I also had this problem. Change filename callback function

 cb(null, new Date().toISOString() + file.originalname);

to

cb(null, new Date().toISOString().replace(/[-T:\.Z]/g, "") + file.originalname);

I think this problem happens because of windows not allowed ':' in filename.

Thank you @yavuz1986 . That solved my issue

I know this is a closed issue. But I wanted to leave my experience here for the next poor soul troubleshooting this bug.

In our case it was a qt frontend sending the files, and I was encountering random failures.

The cause was that qt's multi-part form generation (by default) randomly generates a boundary. If that boundary contains the "/" character, multer will fail to process the form the form data, but will log no error.

Manually setting a random set of boundary characters fixed the issue.

This (for me) looks to be related to https://github.com/expressjs/multer/issues/462.

Same as the guy above, wanna leave my experience in case someone has the same problem.

I was using react-dropzone to get the file. Turns out it gives back an array of files. I set the limit to 1 and thought it is going to be an object and not array for some reason. Sending 0th file in the array from frontend fixed it from me.

Dear Guys I had same problem and I resolved by just replacing the path of uploads
cb(null, 'uploads/') wrong
cb(null, './uploads/') correct

so I got my file uploaded

Love u so much

In Our project, The multer file upload was not working, we checked all the above issue solutions, but in vain. Then we checked deeply and found out that whenever the file upload to server was taking more than 1 minute then file upload was not working and multer was not giving any error and there was cors issue on the frontend. So you can also check the timeout limit set at your server for issue solution. We changed the timeout limit and our uploads started working.

Thanks

When I use below code its working for me on Mac.
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public')
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' +file.originalname )
}
})
Note: request header should file: {binary}

When I use this code it works fine
const upload = multer({ dest: './upload/', })

but when I write it this way it bugs with no errors but this 500 (Internal Server Error)

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'uploads')
    },
    filename: function (req, file, cb) {
        cb(null, new Date().toISOString().replace(/[-T:\.Z]/g, "") + file.originalname);
    }
})

var upload = multer({ storage: storage })

does anyone have an idea why? I've ready all what's above but nothing worked.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

tonghae picture tonghae  路  4Comments

thammarith picture thammarith  路  3Comments

sant123 picture sant123  路  4Comments

adrienbarreau picture adrienbarreau  路  3Comments

Paul-Morris picture Paul-Morris  路  3Comments