我使用Nodejs Multer
angularjs在服务器上上传文件.
我有一个简单的 HTML文件:
我有一个简单的 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.originalname) } }) app.post('/multer',upload.single('photo'),function (req,res) { res.end("File uploaded."); });
这完美地工作,文件成功上传.
但是在上传文件之后,这会将我重定向到“/ multer”(因为表单元素).
我如何留在同一页面??可能使用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上传?
谢谢
Angularjs指令:
原文链接:https://www.f2er.com/angularjs/140946.htmlangular.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.originalname+ '-' + Date.now()+'.jpg') } }); var upload = multer({ storage: storage }); app.post('/multer',upload.single('file'));
请享用!