Devrath
Devrath

Reputation: 42824

Having Error: ENOENT for a simple image upload in server

URL ::

http://<----url---->/Details/?key=image

image is a .jpg file which is the result of a POST request


My Express program::

var express=require('express');
var mysql=require('mysql');
var fs=require('fs');
var http=require('http');

var app=express();

var connection=mysql.createConnection({
    host:'localhost',
    user:'root',
    password:'root',
    database:'posting_only_image_DB'
});

connection.connect();

app.set('port',process.env.PORT||7002);
app.use(express.static(__dirname+'/public/images'));
app.use(express.bodyParser({uploadDir:'./uploads'}));

app.post('/Details/',function(req,res){
    var temp_path=req.files.key.path 
    var target_path='./public/images' + req.files.key.path;

    var path=req.files.key.name;

    connection.query('INSERT INTO MyTable(image)',[path],function(err,rows,fields)
    {
        console.log('Connection result error', +err);
    });

    //Now move the file from temporary location to permanent location
    fs.rename(temp_path,target_path,function(err){
        if(err) throw err;

    //Delete the temporary file
    fs.unlink(temp_path,function(err){
        if(err) throw err;
    });
    });

});

http.createServer(app).listen(app.get('port'),function(){
    console.log('Express server listening on port'+app.get('port'));
});

ERROR i am facing::

Error: ENOENT, rename 'uploads/4542-1jk7wvf.jpg'

note:: My uploads folder is in the place my app.js app is running

Any inputs would be helpful

{EDIT}

{ key: 
   { originalFilename: 'images.jpg',
     path: '/tmp/4645-17577l8.jpg',
     headers: 
      { 'content-disposition': 'form-data; name="key"; filename="images.jpg"',
        'content-type': 'image/jpeg' },
     ws: 
      { _writableState: [Object],
        writable: true,
        domain: null,
        _events: [Object],
        _maxListeners: 10,
        path: '/tmp/4645-17577l8.jpg',

My Edited code::

var express=require('express');
var mysql=require('mysql');
var fs=require('fs');
var http=require('http');
var crypto=require('crypto');

var app=express();

var connection=mysql.createConnection({
    host:'localhost',
    user:'root',
    password:'root',
    database:'posting_only_image_DB'
});

connection.connect();

app.set('port',process.env.PORT||7002);

app.use(express.bodyParser());

app.post('/Details/',function(req,res,next){

    var file_name=req.files.key.originalFilename;
    console.log(file_name);

    crypto.randomBytes(8, function(ex, buf) {

        var array     = req.files.key.originalFilename.split('.');
        var type      = array[array.length - 1];
        var name      = buf.toString('hex') + '.' + type;

        fs.rename(req.files.key.path, './public/images/' + name, function(e) {
            next(e, name);
        });
    });
});

http.createServer(app).listen(app.get('port'),function(){
    console.log('Express server listening on port'+app.get('port'));
});

Upvotes: 0

Views: 2441

Answers (2)

Avinash
Avinash

Reputation: 779

check if your destination path exists. you get this error Error: ENOENT, rename source_path even if the destination doesn't exists or has sufficient permissions.

Upvotes: 0

sbarow
sbarow

Reputation: 2819

I have come across this issue before on my Mac and it had to do with permissions. Change

app.use(express.bodyParser({uploadDir:'./uploads'}));

to

app.use(express.bodyParser());

Then do this to save the file.

crypto.randomBytes(8, function(ex, buf) {

  var array     = req.files.key.name.split('.');
  var type      = array[array.length - 1];
  var name      = buf.toString('hex') + '.' + type;

  fs.rename(req.files.key.path, './public/uploads/' + name, function(e) {
    next(e, name);
  });
});

You get the added benefit of a unique file name. Don't forget to require('crypto')

Edit

When you post from your form

<input type="file" name="key">

The name of name is what you need to use when using req.files.< the name of the input>

Edit 2

To keep the same filename all you would do is (you can get rid of the crypto function)

fs.rename(req.files.key.path, './public/uploads' + req.files.key. originalFilename, function(e) {
    // Do what ever else you need to do.
})

Upvotes: 1

Related Questions