一切正常,期望文件上传。当我通过控制台检查以查看文件字段时,它是一个空字符串,而不是保存到集合中。 我觉得angular.js中存在一些问题,因为我已经在邮递员中对其进行了检查,
前端
这是html代码。
<div ng-controller="postCtrl">
<div>
<form enctype="multipart/form-data">
<input type="text" ng-model="description" placeholder="Write something!">
<input type = "file" file-model = "myFile" name="file"/>
<button ng-click = "addNewPost()">Post</button>
</form>
</div>
<br>
</div>
用于文件元素的angular.js指令
angular.module('fileDirectives', [])
.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.js文件服务
angular.module('postsServices', [])
.service('uploadPost', ['$http', function($http) {
var post = this;
post.uploadIt = function(file, postData) {
console.log(post.file);
var formData = new FormData();
formData.append('file', file);
formData.append('description', postData.description);
formData.append('author', postData.author);
return $http.post('api/posts', formData, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
});
};
}])
angular.js发布控制器
angular.module('postControllers', ['postsServices'])
.controller('postCtrl', ['$scope', '$http', 'uploadPost', function($scope, $http, uploadPost) {
// Get all the post for user timeline
$scope.posts = [];
$http.get('/api/posts').then((posts) => {
$scope.posts = posts.data;
}).catch((err) => {
console.log(err);
});
}]);
后端
GridFS.js
require('./config');
const mongoose = require('mongoose');
const crypto = require('crypto');
const path = require('path');
const multer = require('multer');
const Grid = require('gridfs-stream');
const GridFsStorage = require('multer-gridfs-storage');
const conn = mongoose.createConnection(process.env.MONGODB_URI);
let gfs;
conn.once('open', () => {
gfs = Grid(conn.db, mongoose.mongo);
gfs.collection('media');
});
const storage = new GridFsStorage({
url: process.env.MONGODB_URI,
file: (req, file) => {
return new Promise((resolve, reject) => {
crypto.randomBytes(16, (err, buf) => {
if (err) {
return reject(err);
}
const filename = buf.toString('hex') + path.extname(file.originalname);
const fileInfo = {
filename: filename,
bucketName: 'media'
};
resolve(fileInfo);
});
});
}
});
const upload = multer({ storage });
module.exports = {upload};
帖子的api路线
router.post('/posts', upload.single('file'), (req, res) => {
console.log(req.body);
var post = new Post();
post.author = req.body.author;
post.media = req.body.media;
post.time = new Date().getTime();
post.description = req.body.description;
post.save().then((result) => {
res.json(result);
}).catch((err) => {
res.json(err);
});
});