gpt4 book ai didi

javascript - 如何在 mongodb 中上传文件(不需要使用 BSON 的 gridfs )

转载 作者:行者123 更新时间:2023-12-03 06:27:25 24 4
gpt4 key购买 nike

我正在尝试在 mongodb 中存储文件、图像和文档,但它只需要 null,我能够将文件存储在文件夹中,但无法对 mongo 执行相同的操作。

.ejs 文件如下:

<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>

对应的js文件为::

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);
});
}


}]);

api中的 Controller 文件如下::

 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});


});
} };

api中的模型是::

module.exports = {


schema: true,
attributes: {




up: {
type: 'jpg',
columnName: 'up'
},

title: {
type: 'string',
// required: true
columnName: 'title'
}



}
};

这是我的 sails Controller 代码,带有 gridfs 编码,请看一下。

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});


}

}

}

最佳答案

如果您想将文件存储到 mongoDB 中,请查看 GridFS

GridFS is a specification for storing and retrieving files that exceed the BSON-document size limit of 16 MB.

Instead of storing a file in a single document, GridFS divides the file into parts, or chunks 1, and stores each chunk as a separate document. By default, GridFS uses a chunk size of 255 kB; that is, GridFS divides a file into chunks of 255 kB with the exception of the last chunk. The last chunk is only as large as necessary. Similarly, files that are no larger than the chunk size only have a final chunk, using only as much space as needed plus some additional metadata.

GridFS uses two collections to store files. One collection stores the file chunks, and the other stores file metadata. The section GridFS Collections describes each collection in detail.

When you query GridFS for a file, the driver will reassemble the chunks as needed. You can perform range queries on files stored through GridFS. You can also access information from arbitrary sections of files, such as to “skip” to the middle of a video or audio file.

GridFS is useful not only for storing files that exceed 16 MB but also for storing any files for which you want access without having to load the entire file into memory

关于javascript - 如何在 mongodb 中上传文件(不需要使用 BSON 的 gridfs ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38589329/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com