我正在尝试使用multer将图像上传到我的数据库,当我尝试使用ng-submit上传时,我的图像被保存到我的文件夹中,并且没有路径被保存到数据库,但是第二次尝试之后:将图像保存到文件夹,但是图像名称是我第一次尝试的名称,然后是第三次我再次尝试:图像已上传到文件夹,然后图像名称是我第二次尝试的名称,就像这样:
1st try: image uploaded: apple.jpg result in mongodb: none
2nd try: image uploaded: cicada.jpg result in mongodb: img{1547033391393_apple.jpg}
3rd try image uploaded: logo.jpg result in mongodb: img{1547033119631_cicada.jpg}
这是我的代码,我在哪里做错了?
模式
var NewsfeedSchema = new Schema({
subject: { type: String, required: false},
nw_content: { type: String, required: false, lowercase: false},
img: {type: String,required: false}
});
newsfeed.html
<form ng-submit="newsfeed.regNewsfeed(regData); Submit()">
<input type="text" name="subject" ng-model="newsfeed.regData.subject">
<textarea type="text" name="nw_content" ng-model="newsfeed.regData.nw_content"></textarea>
<label>
Browse
<input type = "file" file-model="file.upload" name="myfile" ng-disbled="uploading">
</label>
<img style = "width:100px">
<button ng-disabled="uploading" type="submit">Send Announcement</button>
</form>
newsfeedCtrl.js
.controller('newsfeedCtrl', function($http, $location, Newsfeed, $route,uploadFile) {
var app = this;
app.file = {};
app.Submit = function(){
$scope.uploading = true;
uploadFile.upload(app.file).then(function(data){
if(data.data.success){
$scope.alert = 'alert alert-success';
$scope.file = {};
} else {
$scope.alert = 'alert alert-danger';
$scope.file = {};
}
})
}
app.regNewsfeed = function(regData) {
Newsfeed.create(app.regData).then(function(data) {
app.successMsg = data.data.message + '...Redirecting';
});
};
});
newsfeedServices.js
.factory('Newsfeed', function($http) {
var newsfeedFactory = {};
newsfeedFactory.create = function(regData) {
return $http.post('/api/upload', regData);
};
newsfeedFactory.upload = function(file){
var fd = new FormData();
fd.append('myfile', file.upload);
return $http.post('/api/upload',fd,{
transformRequest:angular.identity,
headers:{'Content-Type':undefined}
});
};
return newsfeedFactory;
});
api.js
var multer = require ('multer');
var Newsfeed = require('../models/newsfeed');
var imageName;
var storage = multer.diskStorage({
destination:function(req,file,cb){
cb(null,'./public/assets/images');
},
filename:function(req,file,cb){
if(!file.originalname.match(/\.(png|jpg|jpeg)$/)){
var err = new Error();
err.code = 'filetype';
return cb(err);
}else{
imageName = Date.now() + '_' + file.originalname;
cb(null, imageName);
}
}
})
var upload = multer({
storage:storage,
limits:{fileSize:10000000}
}).single('myfile');
const parser = multer({ storage: storage });
router.post('/upload', parser.single("myfile"),function(req,res){
upload(req,res,function(err){
const image = {};
if(err){
console.log(err);
} else {
res.json({success:false,message:'File uploaded!'});
}
})
var newsfeed = new Newsfeed();
newsfeed.subject = req.body.subject;
newsfeed.nw_content = req.body.nw_content;
myImage = imageName.toString('base64');
newsfeed.img = myImage;
newsfeed.save(function(err) {});
})