AngularJS上传文件快递失败
AngularJS failed to upload file express
我正在尝试上传一个文件来表达(这样我可以稍后将其上传到 mongoDB)。然而,当我尝试上传一个文件来表达时,我打印出了响应数据,但似乎没有任何东西被传递进来。
我正在使用 ng-file-upload.min.js。谁能帮我吗?
script.js
var app = angular.module('fileUpload', ['ngFileUpload']);
app.controller('MyCtrl', ['$scope', 'Upload', '$timeout', function ($scope, Upload, $timeout) {
$scope.uploadFiles = function(files, errFiles) {
$scope.files = files;
$scope.errFiles = errFiles;
angular.forEach(files, function(file) {
file.upload = Upload.upload({
url: '/uploadFile',
data: {file: file}
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
});
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
}, function (evt) {
file.progress = Math.min(100, parseInt(100.0 *evt.loaded / evt.total));
});
});
}
}]);
Server.js
var express = require('express');
var path = require('path'); //core module
var databaseUrl = "localhost:27017/DB"; // default env
var bodyParser = require('body-parser');
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + Date.now());
}
});
var upload = multer({ storage : storage}).single('userFile');
// Configure app
var app = express();
// Store all html files in views
app.use(express.static(__dirname + '/views'));
// Parses recived json input
app.use(bodyParser.json());
// Store all js in Scripts folder
app.use(express.static(__dirname + '/scripts'));
// Technology not needed but good practice, especailly when serval people are working on it
app.get('/', function (req, res) {
res.sendFile('index.html');
});
// Listen for Seach collection request
app.post('/uploadFile',function(req,res){
upload(req,res,function(err) {
if(err) {
console.log("Error uploading file");
}else{
var databaseName = "E-learn" , collection = "Uploads";
var data = req.body;
console.log("Got req:"+req);
}
});
});
// Implement a web server to listen to requests on port 4444
app.listen(5555, function(){
console.log('ready on port 5555');
});
Index.html
<!-- Page Content -->
<div class="container" ng-app="fileUpload" ng-controller="MyCtrl">
<div class="panel panel-default">
<div class="panel-heading"><strong>Upload Files</strong> <small>Bootstrap files upload</small></div>
<div class="panel-body">
<!-- Standar Form -->
<h4>Select files from your computer</h4>
<form action="" method="post" enctype="multipart/form-data" id="js-upload-form">
<div class="form-inline">
<div class="form-group">
<input name="userFile" type="file" ngf-select="uploadFiles($files, $invalidFiles)" multiple accept="image/*" ngf-max-height="1000" ngf-max-size="1MB">
</div>
<button type="submit" class="btn btn-sm btn-primary" id="js-upload-submit">Upload files</button>
</div>
</form>
<!-- Drop Zone -->
<h4>Or drag and drop files below</h4>
<div class="upload-drop-zone" id="drop-zone" ngf-drop ngf-select ng-model="files" class="drop-box"
ngf-drag-over-class="'dragover'" ngf-multiple="true" ngf-allow-dir="true"
accept="image/*,application/pdf" ngf-pattern="'image/*,application/pdf'">
Just drag and drop files here
</div>
<!-- Progress Bar
<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%;">
<span class="sr-only">60% Complete</span>
</div>
</div>
-->
<!-- Upload Finished -->
<div class="js-upload-finished">
<h3>Processed files</h3>
<div class="list-group">
<ul>
<li ng-repeat="f in files" style="font:smaller"><span class="badge alert-success pull-right">{{f.name}} {{f.$errorParam}}</span>
<span class="progress" ng-show="f.progress >= 0">
<div style="width:{{f.progress}}%" ng-bind="f.progress + '%'"></div>
</span>
</li>
<li ng-repeat="f in errFiles" style="font:smaller">
{{f.name}} {{f.$error}} {{f.$errorParam}}
</li>
</ul>
{{errorMsg}}
</div>
</div>
</div>
</div>
</div>
结果
上传文件时出错
您的 Express 服务器似乎没有使用任何中间件来接收文件上传。 body-parser 不会为你做这件事。我个人使用 multer.
如前所述,body-parser
不支持文件上传,您需要使用其他模块。这是 formidable.
的简单实现
var async = require('async')
var formidable = require('formidable')
app.post('/uploadFile', function (req, res, next) {
var form = new formidable.IncomingForm()
form.uploadDir = '/my/upload/path'
form.type = 'multipart'
form.multiples = true
form.parse(req, function (err, fields, files) {
if (err) {
return next(err)
}
// Each key in files is a file with the key being the input's name
async.forEachOfSeries(files, function (file, inputName, cb) {
// Do something with the files
}, function (err) {
next(err)
})
})
})
正如 Mitchell Simoens 所说,multer 是一个不错的选择。我猜你需要一些帮助来编写代码。所以这是一个例子。
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + Date.now());
}
});
var upload = multer({ storage : storage}).single('file');
app.post('/uploadFile',function (req,res){
upload(req,res,function (err) {
if (err) {
console.log("Error uploading file");
}
var databaseName = "E-learn" , collection = "Uploads";
var data = req.body;
console.log("Got req:"+req);
});
});
我希望这对你有用
var multer = require('multer');
app.post('/uploadFile',function(req,res){
var your_filename = "";
var storage = multer.diskStorage({ //multers disk storage settings
destination: function (req, file, cb) {
cb(null, __dirname + '/public/uploads/')
},
filename: function (req, file, cb) {
var datetimestamp = Date.now(),
file_name = file.originalname.split(".");
your_filename = file_name[0]+'_'+datetimestamp+'.'+file_name[1];
cb(null, your_filename);
}
});
var upload = multer({ //multer settings
storage: storage
}).single('file');
upload(req,res,function(err){
if(err){
res.json({error_code:1,err_desc:err});
return;
}
res.json({error_code:0,err_desc:null,filename:your_filename});
})
})
如果还是不行,给我发消息
我正在尝试上传一个文件来表达(这样我可以稍后将其上传到 mongoDB)。然而,当我尝试上传一个文件来表达时,我打印出了响应数据,但似乎没有任何东西被传递进来。
我正在使用 ng-file-upload.min.js。谁能帮我吗?
script.js
var app = angular.module('fileUpload', ['ngFileUpload']);
app.controller('MyCtrl', ['$scope', 'Upload', '$timeout', function ($scope, Upload, $timeout) {
$scope.uploadFiles = function(files, errFiles) {
$scope.files = files;
$scope.errFiles = errFiles;
angular.forEach(files, function(file) {
file.upload = Upload.upload({
url: '/uploadFile',
data: {file: file}
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
});
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
}, function (evt) {
file.progress = Math.min(100, parseInt(100.0 *evt.loaded / evt.total));
});
});
}
}]);
Server.js
var express = require('express');
var path = require('path'); //core module
var databaseUrl = "localhost:27017/DB"; // default env
var bodyParser = require('body-parser');
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + Date.now());
}
});
var upload = multer({ storage : storage}).single('userFile');
// Configure app
var app = express();
// Store all html files in views
app.use(express.static(__dirname + '/views'));
// Parses recived json input
app.use(bodyParser.json());
// Store all js in Scripts folder
app.use(express.static(__dirname + '/scripts'));
// Technology not needed but good practice, especailly when serval people are working on it
app.get('/', function (req, res) {
res.sendFile('index.html');
});
// Listen for Seach collection request
app.post('/uploadFile',function(req,res){
upload(req,res,function(err) {
if(err) {
console.log("Error uploading file");
}else{
var databaseName = "E-learn" , collection = "Uploads";
var data = req.body;
console.log("Got req:"+req);
}
});
});
// Implement a web server to listen to requests on port 4444
app.listen(5555, function(){
console.log('ready on port 5555');
});
Index.html
<!-- Page Content -->
<div class="container" ng-app="fileUpload" ng-controller="MyCtrl">
<div class="panel panel-default">
<div class="panel-heading"><strong>Upload Files</strong> <small>Bootstrap files upload</small></div>
<div class="panel-body">
<!-- Standar Form -->
<h4>Select files from your computer</h4>
<form action="" method="post" enctype="multipart/form-data" id="js-upload-form">
<div class="form-inline">
<div class="form-group">
<input name="userFile" type="file" ngf-select="uploadFiles($files, $invalidFiles)" multiple accept="image/*" ngf-max-height="1000" ngf-max-size="1MB">
</div>
<button type="submit" class="btn btn-sm btn-primary" id="js-upload-submit">Upload files</button>
</div>
</form>
<!-- Drop Zone -->
<h4>Or drag and drop files below</h4>
<div class="upload-drop-zone" id="drop-zone" ngf-drop ngf-select ng-model="files" class="drop-box"
ngf-drag-over-class="'dragover'" ngf-multiple="true" ngf-allow-dir="true"
accept="image/*,application/pdf" ngf-pattern="'image/*,application/pdf'">
Just drag and drop files here
</div>
<!-- Progress Bar
<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%;">
<span class="sr-only">60% Complete</span>
</div>
</div>
-->
<!-- Upload Finished -->
<div class="js-upload-finished">
<h3>Processed files</h3>
<div class="list-group">
<ul>
<li ng-repeat="f in files" style="font:smaller"><span class="badge alert-success pull-right">{{f.name}} {{f.$errorParam}}</span>
<span class="progress" ng-show="f.progress >= 0">
<div style="width:{{f.progress}}%" ng-bind="f.progress + '%'"></div>
</span>
</li>
<li ng-repeat="f in errFiles" style="font:smaller">
{{f.name}} {{f.$error}} {{f.$errorParam}}
</li>
</ul>
{{errorMsg}}
</div>
</div>
</div>
</div>
</div>
结果 上传文件时出错
您的 Express 服务器似乎没有使用任何中间件来接收文件上传。 body-parser 不会为你做这件事。我个人使用 multer.
如前所述,body-parser
不支持文件上传,您需要使用其他模块。这是 formidable.
var async = require('async')
var formidable = require('formidable')
app.post('/uploadFile', function (req, res, next) {
var form = new formidable.IncomingForm()
form.uploadDir = '/my/upload/path'
form.type = 'multipart'
form.multiples = true
form.parse(req, function (err, fields, files) {
if (err) {
return next(err)
}
// Each key in files is a file with the key being the input's name
async.forEachOfSeries(files, function (file, inputName, cb) {
// Do something with the files
}, function (err) {
next(err)
})
})
})
正如 Mitchell Simoens 所说,multer 是一个不错的选择。我猜你需要一些帮助来编写代码。所以这是一个例子。
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + Date.now());
}
});
var upload = multer({ storage : storage}).single('file');
app.post('/uploadFile',function (req,res){
upload(req,res,function (err) {
if (err) {
console.log("Error uploading file");
}
var databaseName = "E-learn" , collection = "Uploads";
var data = req.body;
console.log("Got req:"+req);
});
});
我希望这对你有用
var multer = require('multer');
app.post('/uploadFile',function(req,res){
var your_filename = "";
var storage = multer.diskStorage({ //multers disk storage settings
destination: function (req, file, cb) {
cb(null, __dirname + '/public/uploads/')
},
filename: function (req, file, cb) {
var datetimestamp = Date.now(),
file_name = file.originalname.split(".");
your_filename = file_name[0]+'_'+datetimestamp+'.'+file_name[1];
cb(null, your_filename);
}
});
var upload = multer({ //multer settings
storage: storage
}).single('file');
upload(req,res,function(err){
if(err){
res.json({error_code:1,err_desc:err});
return;
}
res.json({error_code:0,err_desc:null,filename:your_filename});
})
})
如果还是不行,给我发消息