Aneh Thakur
Aneh Thakur

Reputation: 1100

upload image node.js express

I'm trying to upload image to server in node.js and express.

My jade image upload form:

include layout
div.container
    h2 Image Upload Form
    form#fileUpload(method="post" action="/upload" enctype="multipart/form-data") 
        label(for="payload") Select a file to upload:     
        input#payload(type="file" name="myFile" accept="image/*") 
        br 
        button#upload Upload

And in my index.js where I handle response and show form are:

router.get('/imageUpload', function(req, res, next){
    res.render('imageUpload', { title: 'Image upload form' });
});

router.post("/upload", function(req, res, next){ 
    console.log(req.files);
});

I am getting undefined error when I try to get req.files; I'm new to node so plz help. Thank you.

Upvotes: 2

Views: 2373

Answers (2)

Aneh Thakur
Aneh Thakur

Reputation: 1100

Finally image uploading is thanx Lucas Costa for help know i share my code

Step 1. Install formidable from official site formidable

Run command on your prompt

npm install formidable@latest

Step 2. My image upload form in .jade

include layout
    div.container
        h2 Image Upload Form
        form#fileUpload(method="post" action="/upload" enctype="multipart/form-data") 
            label(for="payload") Select a file to upload:     
            input#payload(type="file" name="myFile" accept="image/*") 
            br 
            button#upload Upload

Step 3. Add module in your file in my case i have index.js

var express = require('express');
var router = express.Router();
var util = require("util"); 
var fs = require("fs");
var formidable = require('formidable');
var path = require('path');

/* GET home page. */

router.get('/', function(req, res, next) {
    res.render('index', { title: 'Express', dataGet: "data" });
});

router.get('/about', function(req, res, next) {
    res.render('index', { title: 'C' });
});

router.get('/imageUpload', function(req, res, next){
    res.render('imageUpload', { title: 'Image upload form' });
});

router.post("/upload", function(req, res, next){ 
    var form = new formidable.IncomingForm();
    form.parse(req, function(err, fields, files) {
        // `file` is the name of the <input> field of type `file`
        console.log(files);
        res.writeHead(200, {'content-type': 'text/plain'});
        res.write('received upload:\n\n');
        res.end(util.inspect({fields: fields, files: files}));
    });
    form.on('error', function(err) {
        console.error(err);
    });
    form.on('progress', function(bytesReceived, bytesExpected) {
        var percent_complete = (bytesReceived / bytesExpected) * 100;
        console.log(percent_complete.toFixed(2));
    });
    form.on('end', function(fields, files) {
        /* Temporary location of our uploaded file */
        var temp_path = this.openedFiles[0].path;
        /* The file name of the uploaded file */
        var file_name = this.openedFiles[0].name;
        /* Location where we want to copy the uploaded file */
        var new_location = 'F:/node/expressApp/myAppExpress/public/images/';

        fs.readFile(temp_path, function(err, data) {
            fs.writeFile(new_location + file_name, data, function(err) {
                fs.unlink(temp_path, function(err) {
                    if (err) {
                        console.error(err);
                        } else {
                        console.log("success!");
                    }
                });
            });
        });
    });
});

router.get('/:username', function(req, res) {
    // make somethings with username
    var username = req.params.username;
    console.log("get username"+ username);
});

module.exports = router;

All done! Hope this will help some one :-)

Upvotes: 3

BrTkCa
BrTkCa

Reputation: 4783

The undefined is getting because doesn't exists req.files.

Alter to:

console.log(req.body) // or req.body.myFile to get information of the input

For upload image, I suggest you use formidable, somelike this.

Upvotes: 1

Related Questions