微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript-POST http:// localhost:3000/404(未找到)

我正在使用具有上传功能的Web文件浏览器.我正在使用Angular File Upload指令和angular web file browser.

首先,我下载了文件Web浏览器并进行了配置.

其次,我下载了文件上传指令,并逐步进行了所有操作,我的页面运行正常

enter image description here

但是当我尝试上传内容

FileUploader.js:479 POST 07003 404 (Not Found)

我了解FileUploader.js找不到upload.PHP文件,但我将其放在根文件夹中并提供了路径:

  var uploader = $scope.uploader = new FileUploader({
            url: 'upload.PHP'
        });

它是这样的:

enter image description here

angular / app.js:

(function() {
  'use strict';

  window.app = angular.module('filebrowserApp', ['ngRoute', 'jsTree.directive', 'angularFileUpload']).
  config(['$routeProvider',
    function($routeProvider) {
      $routeProvider.
      when('/', {
        templateUrl: '../partials/home.html',
        controller: 'HomeCtrl'
      }).
      otherwise({
        redirectTo: '/home'
      });
    }
  ]);
    window.app.directive('attachable', function(FileUploader) {
        return {
            restrict: 'E',
            replace: true,
            templateUrl:'../partials/upload.html',
            link: function(scope, element, attrs) {
                scope.uploader = new FileUploader();
            }
        }
    })
    ;
}());

服务器/ app.js

   (function() {
'use strict';

var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var fs = require('fs-extra');

var routes = require('./routes.js');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(cookieParser());

app.use(express.static(path.join(__dirname, '../client')));

app.use('/', routes);

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

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

    module.exports = app;
}());

angular / controller.js

(function() {
  'use strict';

  app.controller('HomeCtrl', ['$scope', 'FetchFileFactory', 'FileUploader',
    function($scope, FetchFileFactory, FileUploader, $upload) {

        // ****** file upload *******

            var uploader = $scope.uploader = new FileUploader({
        url: '/upload',
        success: function (fileItem) {
            $scope.alerts.push({
                type: 'success',
                msg: '"' + fileItem.file.name + '" uploaded'
            });
        },
        error: function (fileItem) {
            $scope.alerts.push({
                type: 'danger',
                msg: '"' + fileItem.file.name + '" Failed'
            });
        }
    });


        // FILTERS

        uploader.filters.push({
            name: 'customFilter',
            fn: function(item /*{File|FileLikeObject}*/, options) {
                return this.queue.length < 10;
            }
        });

        // CALLBACKS

        uploader.onWhenAddingFileFailed = function(item /*{File|FileLikeObject}*/, filter, options) {
            console.info('onWhenAddingFileFailed', item, filter, options);
        };
        uploader.onAfteraddingFile = function(fileItem) {
            console.info('onAfteraddingFile', fileItem);
        };
        uploader.onAfteraddingall = function(addedFileItems) {
            console.info('onAfteraddingall', addedFileItems);
        };
        uploader.onBeforeUploadItem = function(item) {
            console.info('onBeforeUploadItem', item);
        };
        uploader.onProgressItem = function(fileItem, progress) {
            console.info('onProgressItem', fileItem, progress);
        };
        uploader.onProgressAll = function(progress) {
            console.info('onProgressAll', progress);
        };
        uploader.onSuccessItem = function(fileItem, response, status, headers) {
            console.info('onSuccessItem', fileItem, response, status, headers);
        };
        uploader.onErrorItem = function(fileItem, response, status, headers) {
            console.info('onErrorItem', fileItem, response, status, headers);
        };
        uploader.onCancelItem = function(fileItem, response, status, headers) {
            console.info('onCancelItem', fileItem, response, status, headers);
        };
        uploader.onCompleteItem = function(fileItem, response, status, headers) {
            console.info('onCompleteItem', fileItem, response, status, headers);
        };
        uploader.onCompleteall = function() {
            console.info('onCompleteall');
        };

        console.info('uploader', uploader);

        // ****** file browser *******

      $scope.fileViewer = 'Please select a file to view its contents';

      $scope.tree_core = {

        multiple: false,  // disable multiple node selection

        check_callback: function (operation, node, node_parent, node_position, more) {
            // operation can be 'create_node', 'rename_node', 'delete_node', 'move_node' or 'copy_node'
            // in case of 'rename_node' node_position is filled with the new node name

            if (operation === 'move_node') {
                return false;   // disallow all dnd operations
            }
            return true;  // allow all other operations
        }
      };

      $scope.nodeselected = function(e, data) {
        var _l = data.node.li_attr;
        if (_l.isLeaf) {
          FetchFileFactory.fetchFile(_l.base).then(function(data) {
            var _d = data.data;
            if (typeof _d == 'object') {

              //https://stackoverflow.com/a/7220510/1015046//
              _d = JSON.stringify(_d, undefined, 2);
            }
            $scope.fileViewer = _d;
          });
        } else {

          //http://jimhoskins.com/2012/12/17/angularjs-and-apply.html//
          $scope.$apply(function() {
            $scope.fileViewer = 'Please select a file to view its contents';
          });
        }
      };


    }
  ]);

}());

Upload.html:

<div ng-if="uploader">

    <div class="container">
        <div class="row">
        <div class="col-md-3">
        <h3>Select files</h3>
        <input type="file" nv-file-select="" uploader="uploader"/>
        </div>
        <div class="col-md-9" style="margin-bottom: 40px">

        <h3>Upload queue</h3>
        <p>Queue length: {{ uploader.queue.length }}</p>

        <table class="table">
        <thead>
        <tr>
        <th width="50%">Name</th>
        <th ng-show="uploader.isHTML5">Size</th>
        <th ng-show="uploader.isHTML5">Progress</th>
        <th>Status</th>
        <th>Actions</th>
        </tr>
        </thead>
        <tbody>
        <tr ng-repeat="item in uploader.queue">
        <td><strong>{{ item.file.name }}</strong></td>
        <td ng-show="uploader.isHTML5" Nowrap>{{ item.file.size/1024/1024|number:2 }} MB</td>
        <td ng-show="uploader.isHTML5">
        <div class="progress" style="margin-bottom: 0;">
        <div class="progress-bar" role="progressbar" ng-style="{ 'width': item.progress + '%' }"></div>
        </div>
        </td>
        <td class="text-center">
        <span ng-show="item.isSuccess"><i class="glyphicon glyphicon-ok"></i></span>
        <span ng-show="item.isCancel"><i class="glyphicon glyphicon-ban-circle"></i></span>
        <span ng-show="item.isError"><i class="glyphicon glyphicon-remove"></i></span>
        </td>
        <td Nowrap>
        <button type="button" class="btn btn-success btn-xs" ng-click="item.upload()" ng-disabled="item.isReady || item.isuploading || item.isSuccess">
        <span class="glyphicon glyphicon-upload"></span> Upload
        </button>
        <button type="button" class="btn btn-warning btn-xs" ng-click="item.cancel()" ng-disabled="!item.isuploading">
        <span class="glyphicon glyphicon-ban-circle"></span> Cancel
        </button>
        <button type="button" class="btn btn-danger btn-xs" ng-click="item.remove()">
        <span class="glyphicon glyphicon-trash"></span> Remove
        </button>
        </td>
        </tr>
        </tbody>
        </table>

        <div>
        <div>
        Queue progress:
        <div class="progress" style="">
        <div class="progress-bar" role="progressbar" ng-style="{ 'width': uploader.progress + '%' }"></div>
        </div>
        </div>
        <!--<button type="button" class="btn btn-success btn-s" ng-click="uploader.uploadAll()" ng-disabled="!uploader.getNotUploadedItems().length">-->
        <!--<span class="glyphicon glyphicon-upload"></span> Upload all-->
        <!--</button>-->
        <!--<button type="button" class="btn btn-warning btn-s" ng-click="uploader.cancelAll()" ng-disabled="!uploader.isuploading">-->
        <!--<span class="glyphicon glyphicon-ban-circle"></span> Cancel all-->
        <!--</button>-->
        <!--<button type="button" class="btn btn-danger btn-s" ng-click="uploader.clearQueue()" ng-disabled="!uploader.queue.length">-->
        <!--<span class="glyphicon glyphicon-trash"></span> Remove all-->
        <!--</button>-->
        </div>
        </div>
        </div>
    </div>

</div>

route.js

(function() {

  'use strict';
  var express = require('express');
  var router = express.Router();
  var fs = require('fs');
  var path = require('path');

  /* GET home page. */
  router.get('/', function(req, res) {
    res.render('index');
  });

  /* Serve the Tree */
  router.get('/api/tree', function(req, res) {
    var _p;
    if (req.query.id == 1) {
      _p = path.resolve(__dirname, '..', 'node_modules');
      processReq(_p, res);

    } else {
      if (req.query.id) {
        _p = req.query.id;
        processReq(_p, res);
      } else {
        res.json(['No valid data found']);
      }
    }
  });

  /* Serve a Resource */
  router.get('/api/resource', function(req, res) {
    res.send(fs.readFileSync(req.query.resource, 'UTF-8'));
  });

  function processReq(_p, res) {
    var resp = [];
    fs.readdir(_p, function(err, list) {
      for (var i = list.length - 1; i >= 0; i--) {
        resp.push(processNode(_p, list[i]));
      }
      res.json(resp);
    });
  }

  function processNode(_p, f) {
    var s = fs.statSync(path.join(_p, f));
    return {
      "id": path.join(_p, f),
      "text": f,
      "icon" : s.isDirectory() ? 'jstree-custom-folder' : 'jstree-custom-file',
      "state": {
        "opened": false,
        "disabled": false,
        "selected": false
      },
      "li_attr": {
        "base": path.join(_p, f),
        "isLeaf": !s.isDirectory()
      },
      "children": s.isDirectory()
    };
  }

  module.exports = router;

}());

我的错误在哪里?感谢您的帮助.

我用这个example并完全删除了我的upload.PHP,固定为server / app.j和controller.js,但是仍然出现相同的错误

更新

我把这段代码放到route.js

var multer  =   require('multer');
var storage =   multer.diskStorage({
    destination: function (req, file, callback) {
        callback(null, './upload');
    },
    filename: function (req, file, callback) {
        callback(null, file.fieldname + '-' + Date.Now());
    }
});
var upload = multer({ storage : storage}).single('test');

router.post('/',function(req,res){
    upload(req,res,function(err) {
        if(err) {
            return res.end("Error uploading file.");
        }
        res.end("File is uploaded");
    });
});

现在发布返回200,但文件夹“上载”中没有任何内容.有什么想法,现在怎么了?

解决方法:

错误是POST http:// localhost:3000/404(未找到)

您没有/的发布路线

您可以这样创建一个

router.post(‘/’,function(req,res){
    //做一些带有req.body或req.files的操作
});

而且,我建议使用express或upload.PHP

要使用express,您还需要更新您的角度FileUploader网址

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐