在MEAN app中使用multer上传文件

时间:2017-08-01 17:14:54

标签: angularjs node.js express multer

我需要你的帮助,这非常重要,因为停止我的应用程序进度。我尝试了一切,但我很困惑。我尝试使用multer上传文件,如果我使用POSTMAN作为我的代码,我得到响应'File uploaded',一切似乎都没问题,但没有任何事情发生,req.file is undefined并且不知道如何改变它。请查看我的代码

服务器

var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var morgan = require('morgan');
var path = require('path');
var multer = require('multer');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var router = express.Router();
var appRoutes = require('./app/routes/api')(router,multer,path);
var passport = require('passport');
var social = require('./app/passport/passport')(app,passport);
var product = require('./app/seed/product-seeder');

app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(__dirname + '/public'));
app.use('/api', appRoutes);

mongoose.connect('mongodb://localhost:27017/tutorial', function(err){
if(err){
    console.log('MongoDB not connected' + err)
} else {
    console.log('Scuccessfully connected to MongoDB database');
}
})
app.get('*', function(req, res){
res.sendFile(path.join(__dirname + '/public/app/views/index.html'))
})

app.listen(port, function(){
console.log('Running the server on port ' + port)
});

API

module.exports = function(router,multer,path) {
var storage = multer.diskStorage({
destination: function(req, file, callback) {
    callback(null, './uploads')
},
filename: function(req, file, callback){
    callback(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
}
})
router.post('/courses/files', function(req, res) {
   var upload = multer({ storage: storage }).single('file')
   upload(req, res, function(err) {
      res.end('File is uploaded')
      console.log(req.file)
   })
   })

    return router
}

服务

userFactory.storeFile = function(file){
    return $http.post('/api/courses/files', file)
}

HTML

<div class="container management-user">
  <form enctype="multipart/form-data" name="sendFile" ng-submit="product.sendFile(file)" novalidate>
    <input type="file" name="file" id="imgInp">
    <input type="submit" value="submit">
  </form>
</div>

控制器

app.sendFile = function(file, valid) {        
    User.storeFile(app.file).then(function(data){  
        console.log(data)
    });
}

1 个答案:

答案 0 :(得分:1)

尝试使用如下指令

.directive('fileModel', ['$parse', function($parse) {
        function fn_link(scope, element, attrs) {
            var onChange = $parse(attrs.fileModel);
            element.on('change', function (event) {
                onChange(scope, { $files: event.target.files });
            });
        };
        return {
            link: fn_link
        }
    }])

然后将input type = file替换为

<input type="file" id="fileId" accept="image/*" file-model="myFiles($files)"/>

然后在您的控制器中添加此

var formData = new FormData();
        $scope.myFiles = function($files) {
            formData.append('img', $files[0]);
}

替换&#39; img&#39;到后端需要的名称 如果您想添加内容,请使用formData中的键添加每个值以发送

formData.append('title', form.title);

和你的$ http方法

$http.post('/api/courses/files', formData).then(...)

节点侧 然后使用multer diskStorage将文件上传到服务器

var uploadMulter = multer.diskStorage({
     destination: function(req, file, callback) {
         callback(null, "./UploadDir");
     },
     filename: function(req, file, callback) {
         callback(null,  Date.now() + path.extname(file.originalname));
     }
 });

var upload = multer({ storage: uploadMulter });

./ UploadDir 是您要上传文件的目标文件夹

最后是你的路由器

router.post('/courses/files',  upload.single('img'), function(req,res){
console.log(req.file);});

现在,如果您要上传单个文件,请使用 upload.single(&#39; img&#39;) **或多次使用** upload.array(&#39; img&#39;,3)此处将上传3个文件。根据需要改变。

如果无法访问目的地目录UploadDir,请尝试通过

加入
app.use('/UploadDir', express.static(path.join(__dirname, 'UploadDir')))