【问题标题】:nodejs + multer + angularjs for uploading without redirectingnodejs + multer + angularjs 无需重定向即可上传
【发布时间】:2016-01-02 14:32:18
【问题描述】:

我正在使用 Nodejs + Multer +angularjs 在服务器上上传文件。

我有一个简单的 HTML 文件:

<form action="/multer" method="post" enctype="multipart/form-data">
<input type="file" id="photo" name="photo"/> 
<button id="Button1">Upload</button>
</form>

Nodejs部分:

var multer  = require('multer');

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './uploads/')
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname)
    }
})

app.post('/multer', upload.single('photo'), function (req, res) {
    res.end("File uploaded.");
});

完美运行,文件已成功上传。

但这会在上传文件后将我重定向到“/multer”(因为 form 元素)。
我如何留在同一页面上??..可能使用 angularjs
所以我尝试了这个:

制作 HTML 角度文件:

<section data-ng-controller="myCtrl">
<input type="file" id="photo" name="photo"/> 
<button id="Button1" ng-click="f()">Upload</button>
</section>

还有一个 Angularjs 控制器:

angular.module('users').controller('myCtrl',[$scope,function($scope){
    $scope.f=function(){
        var photo = document.getElementById('photo');
        var file = photo.files[0];
        if (file) {

            //code to make a post request with a file object for uploading?????

            //something like..
            //$http.post('/multer', file).success(function(response) {
            //console.log("success");
            //});
        }
    }
}]);


有人可以帮助我使用来自 ANGULARJS 控制器的 MULTER 发出带有文件对象的 POST 请求的代码吗?

谢谢

【问题讨论】:

  • 你找到解决办法了吗?
  • @SimranKaur 是的,我找到了解决方案:)
  • @SimranKaur 我已经发布了答案
  • 嗨@GauravGupta 我遇到了同样的问题。请帮助我节省时间。

标签: angularjs node.js multer


【解决方案1】:

Angularjs 指令:

angular.module('users').directive('fileModel', ['$parse', function ($parse) {
return {
    restrict: 'A',
    link: function(scope, element, attrs) {
        var model = $parse(attrs.fileModel);
        var modelSetter = model.assign;

        element.bind('change', function(){
            scope.$apply(function(){
                modelSetter(scope, element[0].files[0]);
            });
        });
    }
};
}]);

Angular html 文件:

<input type="file" file-model="myFile"/><br><br>
<button ng-click="uploadFile()">Upload</button>

Angularjs 控制器:

$scope.uploadFile = function(){

        var file = $scope.myFile;
        var uploadUrl = "/multer";
        var fd = new FormData();
        fd.append('file', file);

        $http.post(uploadUrl,fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(function(){
          console.log("success!!");
        })
        .error(function(){
          console.log("error!!");
        });
    };

Nodejs 服务器路由文件:

var multer  = require('multer');
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './uploads/')
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname+ '-' + Date.now()+'.jpg')
    }
});
var upload = multer({ storage: storage });

app.post('/multer', upload.single('file'));

享受吧!

【讨论】:

  • 为此,“fd.append('file', file)”和“upload.single('file')” - 非常感谢!
  • 给我 {Error: Not Found: POST /multer in the terminal and POST XHR https://..../multer [HTTP/1.1 404 Not Found 220ms] 在资源管理器调试器中怎么能我解决这个问题?
  • 你能告诉我这个 Nodejs 服务器路由文件代码将添加到哪里,因为我是 angularjs 的新手,我无法理解这部分。
  • @noags 尝试在开始时保留 app.js 中的更改,就在您定义 app.js 之后。大多数情况下,您在错误处理程序之后拥有它。
  • 感谢您的解决方案。成功集成到基于Angular-Fullstack-Generator和Yeoman生成的项目中添加到相关API的controller中
猜你喜欢
  • 2020-03-12
  • 1970-01-01
  • 1970-01-01
  • 2018-07-17
  • 2014-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-19
相关资源
最近更新 更多