Search code examples
angularjsnode.jsng-file-upload

"NetworkError: 404 Not Found" when i upload a file using AngularJS and Node.JS


I'm facing this error when I want to upload a file :

"NetworkError: 404 Not Found - http://127.0.0.1:8080/src/img"

404: Not found

This is the code of my page view:

           <div class="col-sm-10">
              <input type="file" ngf-select="uploadFiles($file)"
                     accept="image/*" ngf-max-height="1000" ngf-max-size="1MB">
            </div>

I'm using ngFileUpload module

My controller :

$scope.uploadFiles = function(file){
  if (file) {
     file.upload = Upload.upload({
         url: 'img',
         data: {file: file}
     });

     file.upload.then(function (response) {
     $timeout(function () {
         console.log(response.data);
     });
     }, function (response) {
     if (response.status > 0)
         console.log(response.status + ': ' + response.data);
  });
 }
}

When I test the link: http://127.0.0.1:8080/src/img in my browser works fine but in my app doesn't work, and I get the above error.

What am I doing wrong?


Solution

  • You can use Multer npm module to upload files in Node.js. It would be very easy if you are using express for routing. It can be used as a middleware.

    From their website:

    var express = require('express')
    var multer  = require('multer')
    var upload = multer({ dest: 'uploads/' })
    
    var app = express()
    
    app.post('/profile', upload.single('avatar'), function (req, res, next) {
      // req.file is the `avatar` file 
      // req.body will hold the text fields, if there were any 
    })
    
    app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
      // req.files is array of `photos` files 
      // req.body will contain the text fields, if there were any 
    })
    
    var cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
    app.post('/cool-profile', cpUpload, function (req, res, next) {
      // req.files is an object (String -> Array) where fieldname is the key, and the value is array of files 
      // 
      // e.g. 
      //  req.files['avatar'][0] -> File 
      //  req.files['gallery'] -> Array 
      // 
      // req.body will contain the text fields, if there were any 
    })
    

    The file will be saved in uploads directory with a long and wierd file name but you can access the original file name using req object, for example req.file.originalname for single file upload. You can then use fs.readFile and fs.writeFile to move that file to required location with acutall filename.