I am facing an issue with storing files, images, and documents in MongoDB. Currently, it only accepts null values. Despite being able to store the file in a folder successfully, I am encountering difficulties when trying to do the same in Mongo.
Below is the content of the .ejs file:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js">
</script>
</head>
<div class="container">
<div class="row" ng-controller="PatientEmrController">
<h1>Upload a file</h1>
<div class="col-sm-4">
<form ng-submit="uploadFile()" class="form">
<input type="text" placeholder="title" ng-model="titleText" class="form-control" required>
<br><br>
<file-field ng-model="uploadThis" class="btn" ng-class="{'btn-success':uploadThis}" preview="uploadPreview" name="up" accept="image/png,image/jpg,image/jpeg">Select file</file-field>
<br><br>
<input type="submit">
</form>
</div>
<div class="col-sm-4">
<img ng-src="{{uploadPreview}}" ng-if="uploadPreview" class="img-responsive" >
</div>
</div>
</div> </html>
The corresponding JavaScript file looks like this::
sample.controller('PatientEmrController',['$scope','$http',function($scope,$http){
$scope.uploadFile=function(){
if(!$scope.uploadThis){
alert('Please select a file to upload.')
return;
}
var fd = new FormData();
//you can also send other fields
//this will be available as req.body.title
//NOTE: files must be added AFTER other form data
fd.append('title', $scope.titleText);
//nacho relates to what we called the file
//in the api on sails
fd.append('nacho', $scope.uploadThis);
$http.post('/api/burrito', fd, {
//transformRequest: angular.identity,
//headers: {'Content-Type': undefined}
up:$scope.uploadThis,
title: $scope.titleText,
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(data){
console.log('upload data',data);
if(data.result){
alert('file uploaded. See .tmp/uploads folder.');
}
})
.error(function(err){
alert('there was an error uploading the file.');
console.log(err);
});
}
}]);
The controller file in API is structured as follows::
module.exports = {
torta:function(req,res){
console.log('form body',req.body);
req.file('nacho').upload(function(err,files){
Filecontroller2.create({
up: req.param('up'),
title: req.param('title')
})
.exec(function createCB(err, created){
if (err)
{
return res.negotiate(err);
}
else
{
return res.ok();
}
});
if(err) return res.send(400,{result:false,error:err});
if(!files) return res.send(400,{result:false,error:'Unable to upload file'});
console.log('file data',err,files);
console.log('uploaded file path',files[0].fd)
res.send({result:true,files:files});
});
} };
The model in API is as shown below::
module.exports = {
schema: true,
attributes: {
up: {
type: 'jpg',
columnName: 'up'
},
title: {
type: 'string',
// required: true
columnName: 'title'
}
}
};
This particular code snippet from my Sails controller includes GridFS coding. Please review it thoroughly.
uploadAvatar: function (req, res) {
console.log('form body',req.body);
var patientID=req.session.me;
req.file('avatar').upload(function(err,files){
// don't allow the total upload size to exceed ~10MB
//maxBytes: 10000000
adapter: require('skipper-gridfs'),
//uri: 'mongodb://[username:password@]host1[:port1][/[database[.bucket]]'
uri:'mongodb://kal:kal@localhost:27017/medoolDB.bucket',
},function whenDone(err, uploadedFiles) {
if (err) {
return res.negotiate(err);
return res.ok();
}
// If no files were uploaded, respond with an error.
if (uploadedFiles.length === 0){
return res.badRequest('No file was uploaded');
}
filecontroller2.findOne({patientID:patientID}, function foundFilecontroller(err, fcontroller) {
console.log(req.method);
if (err) return next(err);
if (!fcontroller){
filecontroller2.create({
up:req.param('up'),
})
.exec(function createCB(err, created){
if (err)
{
return res.negotiate(err);
}
else
{
return res.ok();
}
});
}
else
{
// Save the "fd" and the url where the avatar for a user can be accessed
filecontroller2.update({ patientID:patientID}, {
// Generate a unique URL where the avatar can be downloaded.
avatarUrl: require('util').format('%s/user/avatar/%s', sails.getBaseUrl(), req.session.me),
// Grab the first file and use it's `fd` (file descriptor)
avatarFd: uploadedFiles[0].fd
})
.exec(function (err){
if (err) return res.negotiate(err);
return res.ok();
});
if(err) return res.send(400,{result:false,error:err});
if(!files) return res.send(400,{result:false,error:'Unable to upload file'});
console.log('file data',err,files);
console.log('uploaded file path',files[0].fd)
//send response
//result:true -- file upload successful
//files:files -- send uploaded file data to the front end
res.send({result:true,files:files});
}
}
}