2

I'm working on handling file uploads using express.js ,node, and angular. The basic functionality working for small size images. While i try to upload larger images, i got 404 error . I use angular-file-upload. This is my file upload codings

$upload.upload({
            url: '/products/image/upload',
            data: {
                PRODUCT_ID : productId,
            },
            file: file
        }).progress(function(evt){
            console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total, 10));
        }).success(function(data){
            console.log(data);

        });

This is my express js code

app.post('/products/image/upload', controller.uploadProductImage);


exports.uploadProductImage = function(req, res){
var fileObject = req.files.file;
var newPath = '';

    var newFilename = 'sample.png';
newPath = './uploads/products/' + newFilename;

fs.rename(fileObject.path, newPath, function(err) {
    if (err) throw err;
    fs.unlink(fileObject.path , function() {
        if (err) throw err;
        });
    });
res.json({success:true});

};

I have posted here only the sample code. It works good for smaller size image. But if i upload a large size images, the route is shown as 404 error message. I hope it would be some config issue, like memory, process limit. I am not sure what is the exact problem .

I have tried to set the limit in express script like

app.use(express.limit('2mb'));

It is not worked for me. And i tried

node --max-old-space-size=2000 app.js

Bad luck. Please help me to resolve this problem

Thanks in advance

1
  • maybe stream your file ? Commented Apr 5, 2014 at 11:01

1 Answer 1

3

I have been trying to get my head around file uploads using Angular, Node, and Express myself. I am using Express v4.1 with connect-busboy and have the following Node, Express Code working with Daniel Farids angular-file-upload module.

SERVER.JS

    var express = require('express');       //Express Web Server
    var busboy = require('connect-busboy'); //middleware for form/file upload
    var path = require('path');             //used for file path
    var fs = require('fs-extra');           //File System - for file manipulation
    var util = require('util');         

    var app = express();
    app.use(busboy());
    app.use(express.static(path.join(__dirname, 'public')));

    /* ==========================================================
    Create a Route (/upload) to handle the Form submission
    (handle POST & PUT requests to /upload)
    Express v4 Route definition
    ============================================================ */
    app.route('/upload')
    .post(function (req, res, next) {
      var arr;
      var fstream;
      var filesize = 0;
      req.pipe(req.busboy);

      req.busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {        
        //uploaded file name, encoding, MIME type
        console.log('File [' + fieldname +']: filename:' + filename + ', encoding:' + 
             encoding + ', MIME type:'+ mimetype);

        //uploaded file size
        file.on('data', function(data) {
          console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
          fileSize = data.length;
          console.log("fileSize= " + fileSize);
        });

        file.on('end', function() {
          console.log('File [' + fieldname + '] ENDed');
          console.log("-------------------------");
        });

        /*
        populate array
        I am collecting file info in data read about the file. It may be more correct to  
        read file data after the file has been saved to img folder i.e. after  
        file.pipe(stream) completes the file size can be got using stats.size as shown 
        below
        */
        arr= [{fieldname: fieldname, filename: filename, encoding: encoding, MIMEtype:   
            mimetype}];

        //Path where image will be uploaded
        fstream = fs.createWriteStream(__dirname + '/img/' + filename);
        //create a writable stream

        file.pipe(fstream);                         //pipe the post data to the file

        //stream Ended - (data written) send the post response
        req.on('end', function () {
        res.writeHead(200, {"content-type":"text/h tml"});  //http response header

        //res.end(JSON.stringify(arr)); //http response body - send json data
      });

      //Finished writing to stream
      fstream.on('finish', function () {
        console.log('Finished writing!');

        //Get file stats (including size) for file saved to server
        fs.stat(__dirname + '/img/' + filename, function(err, stats) {
          if(err)
            throw err;    
        //if a file
          if (stats.isFile()) {
            //console.log("It\'s a file & stats.size= " + JSON.stringify(stats));
            console.log("File size saved to server: " + stats.size);    
            console.log("-----------------------");
          };
        });
      });

       // error
       fstream.on('error', function (err) {
         console.log(err);
       });
      });   // @END/ .req.busboy
    })  // @END/ POST

See [My GitHub] (https://github.com/mick26/ng_Node-AdvancedFileUpload)

Note with express 4.1 alot of the middleware built into express 3.x is omitted. You will not be able to use req.files as this function is part of a third party middleware called 'formidable' which was used by another middleware called 'bodyParser'. Both formidable and body-parser are still available on NPM I think. Instead I used an npm module called connect-busboy and streamed the data. I just checked the program and uploaded a file of >320M successfully. Hope this can help you.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.