How to upload file to mongodb on mongoose using nestJS? - mongodb
Hello pls do somebody know how to upload file to MongoDB (mongoose) using nestJS ??
I already have the ability to #Post upload file to my nestJS projet and #Get, but know I wanna post to mongodb using mongoose, pls help
I don't recommend to store images on your database but you can do this:
async function saveFile(file: Express.Multer.File){
//Convert the file to base64 string
const fileB64 = file.buffer.toString('base64')
//userModel is a mongoose model
//Store the string
await this.userModel.create({file: fileB64})
}
async function getFile(userId: string){
//Get user from database
const user = await this.userModel.findOne({_id: userId}).lean()
if(!user) throw new NotFoundException('User not found')
const file = user.file
//Convert the string to buffer
return Buffer.from(file, 'base64')
}
First you have to convert that file to a string with base64 encoding then you can save that string on your database with the create method or updating a document.
If you want to get that file just search that info in your database and then convert the string to buffer and return it.
Like I said before, I don't recommend this it is better if you upload the buffer to s3 and save the link on your database.
thanks it is worked, but it is only buffer a can't see the image! please is there any others option to get is as image? please here what i'm getting :
{"type":"Buffer","data":[255,216,255,224,0,16,74,70,73,70,0,1,1,0,0,72,0,72,0,0,255,225,0,120,69,120,105,102,0,0,73,73,42,0,8,0,0,0,4,0,18,1,3,0,1,0,0,0,1,0,0,0,49,1,2,0,7,0,0,0,62,0,0,0,18,2,3,0,2,0,0,0,2,0,2,0,105,135,4,0,1,0,0,0,70,0,0,0,0,0,0,0,71,111,111,103,108,101,0,0,3,0,0,144,7,0,4,0,0,0,48,50,50,48,2,160,4,0,1,0,0,0,208,2,0,0,3,160,4,0,1,0,0,0,0,5,0,0,0,0,0,0,255,192,0,17,8,5,0,2,208,3,1,34,0,2,17,1,3,17,1,255,196,0,31,0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0,0,1,2,3,4,5,6,7,8,9,10,11,255,196,0,181,16,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125,1,2,3,0,4,17,5,18,33,49,65,6,19,81,97,7,34,113,20,50,129,145,161,8,35,66,177,193....
Angular service file
postFile(fileToUpload: File): Observable<any> {
const formaData: FormData = new FormData();
formaData.append('fileKey', fileToUpload, fileToUpload.name);
return this.http.post(`${this.backEndURL}/api/prods/upload/two/tree/`, JSON.stringify(formaData));}
but my backend Nestjs trow error:
[ExceptionsHandler] Cannot read property 'buffer' of undefined +80859ms
TypeError: Cannot read property 'buffer' of undefined
Related
Upload Blob Url to Firebase Storage | Flutter
So I already read about the topic but I simply didn't understand the solutions on stack. I came up with this code: Im saving a url looking like this: final String myDataUrl = file.url; print(myDataUrl); blob:http://localhost:51947/2952a3b1-db6a-4882-a42a-8e1bf0a0ad73 & then Im trying to add it into Firebase Storage with the putString operator, that I guessed that suited me best while reading the Documentation. I thought that I have a Url and therefore should be able to upload it like this: FirebaseStorage.instance .ref() .child("bla") .putString(myDataUrl, format: PutStringFormat.dataUrl); But it doesn't work, it says that: Error: Invalid argument (uri): Scheme must be 'data': Instance of '_Uri' So Im guessing that it somehow can't format my url to one that is accepted. What can I do different to upload a blob successfully to firebase Storage? -----------------Answer---------------------- Answer in the comment of the answer. You have to convert your Blob to a Uint8List & upload it like: Future<Uint8List> fileConverter() async { final reader = html.FileReader(); reader.readAsArrayBuffer(file!); await reader.onLoad.first; return reader.result as Uint8List; } and then put it into your Storage: Future uploadFile(String uid) async { if (file == null) return; final path = "nachweise/$uid"; Uint8List fileConverted = await fileConverter(); try { FirebaseStorage.instance .ref() .child(path) .putData(fileConverted) .then((bla) => print("sucess")); } on FirebaseException catch (e) { return null; } }
The Firebase Storage SDKs can upload local data as either a File, an array of bytes, or a base-64 encoded string. The only URLs it accepts are so-called data URLs, which start with data:// and contain the complete data of the object. They cannot upload data directly from URLs that you more commonly see, such as http:// or https://. You'll need to first download the data from that URL to the local device, and then upload it from there.
Uploading images to s3 through stitch aws service fails
Sorry I am a noob, but I am building a quasar frontend using mongodb stitch as backend. I am trying to upload an image using the stitch javascript sdks and the AwsRequest.Builder. Quasar gives me an image object with base64 encoded data. I remove the header string from the base64 string (the part that says "data:image/jpeg;base64,"), I convert it to Binary and upload it to the aws s3 bucket. I can get the data to upload just fine and when I download it again I get the exact bytes that I have uploaded, so the roundtrip through stitch to aws S3 and back seems to work. Only, the image I upload can neither be opened in S3 nor cannot be opened once downloaded. The difficulties seem to be in the conversion to binary of the base64 string and/or in the choice of the proper upload parameters for stitch. Here is my code: var fileSrc = file.__img.src // valid base64 encoded image with header string var fileData = fileSrc.substr(fileSrc.indexOf(',') + 1) // stripping out header string var body = BSON.Binary.fromBase64(fileData, 0) // here I get the BSON error const args = { ACL: 'public-read', Bucket: 'elever-erp-document-store', ContentType: file.type, ContentEncoding: 'x-www-form-urlencoded', // not sure about the need to specify encoding for binary file Key: file.name, Body: body } const request = new AwsRequest.Builder() .withService('s3') .withRegion('eu-west-1') .withAction('PutObject') .withArgs(args) aws.execute(request.build()) .then(result => { alert('OK ' + result) return file }).catch(err => { alert('error ' + err) }) In the snippet above I try to use BSON.Binary.fromBase64 for the conversion to binary as per Haley's suggestion below, but I get following error: boot_stitch__WEBPACK_IMPORTED_MODULE_3__["BSON"].Binary.fromBase64 is not a function. I have also tried other ways to convert the base64 string to binary, like the vanilla atob() function and the BUFFER npm module, but with no joy. I must be doing something stupid somewhere but I cannot find my way out.
I had a similar issue, solved it by creating a buffer from the base64 data and then used new BSON.Binary(new Uint8Array(fileBuffer), 0) to create the BSON Binary Object. Using the OP it would look something like this: var fileSrc = file.__img.src // valid base64 encoded image with header string var fileData = fileSrc.substr(fileSrc.indexOf(',') + 1) // stripping out header string var fileBuffer = new Buffer(fileData, 'base64'); var body = new BSON.Binary(new Uint8Array(fileBuffer), 0)
You should be able to convert the base64 image to BSON.Binary and then upload the actual image that way (i have some of the values hard-coded, but you can replace those): context.services.get("<aws-svc-name>").s3("<your-region>").PutObject({ Bucket: 'myBucket', Key: "hello.png", ContentType: "image/png", Body: BSON.Binary.fromBase64("iVBORw0KGgoAA... (rest of the base64 string)", 0), })
Read Uint8Array buffer from Collection and download as pdf
I saved a pdf file in a collection using this function: /*** client.js ***/ // asign a change event into input tag 'change input' : function(event,template){ var file = event.target.files[0]; //assuming 1 file only if (!file) return; var reader = new FileReader(); //create a reader according to HTML5 File API reader.onload = function(event){ var buffer = new Uint8Array(reader.result) // convert to binary Meteor.call('saveFile', buffer); } reader.readAsArrayBuffer(file); //read the file as arraybuffer } /*** server.js ***/ Files = new Mongo.Collection('files'); Meteor.methods({ 'saveFile': function(buffer){ Files.insert({data:buffer}) } }); How can I read it again from the collection and provide a download link that the user can download the file as a pdf and save it on the local computer?
It depends on what the data type ends up to be on the front-end when you see that document record in your MiniMongo collection. What you want to do is to convert that Uint8Array data to a base64-encoded data URL and provide a Download PDF link after you get the data in the browser. Meteor does not support serving files from the server out of the box, so you'll likely have to publish that file's blob via mongo->minimongo publication/subscription mechanism and then use the HTML data-uri API to get it like I've just described.
Get undefined variable trying to update the path to an uploaded file within MongoDB using angular-file-upload and MEAN.js
If someone could help me I would be eternally grateful. I have been slamming my head against a brick wall for weeks trying to get images to upload the way it is demonstrated out of the box with the MEAN.js users module. In the generated users module the file is uploaded into a directory and the path to that file is stored in a field in the mongodb document. I can get the file to upload to where it needs to go using multer and the fileupload function. However, I cannot save the path to the field within the document. I cannot figure out how to avoid getting an 'undefined' variable. I've tried creating a $window service and passing data to it as a global variable and a bunch of other things and I'm totally stuck. I have commented the code below to demonstrate what is going awry in my server controller changeShoePicture function. // This is the boilerplate code from the mean.js "users" module. // I can not create a $window service or global variable to store the // shoe data below so that I can update the shoe.shoeImageURL field // in MongoDB with path to the successfully uploaded file. exports.changeShoePicture = function (req, res) { var message = null; var shoe = req.shoe; var upload = multer(config.uploads.shoeUpload).single('newProfilePicture'); var profileUploadFileFilter = require(path.resolve('./config/lib/multer')).profileUploadFileFilter; console.log('i am here', shoe); // shoe is defined here. // Filtering to upload only images. This works and proceeds to the else condition! upload.fileFilter = profileUploadFileFilter; upload(req, res, function (uploadError) { if(uploadError) { return res.status(400).send({ message: 'Error occurred while uploading profile picture' }); } else { //shoe image file is successfully uploaded to the location on the server, // However the following fails because the shoe variable is undefined. shoe.shoeImageURL = config.uploads.shoeUpload.dest + req.file.filename; } });
To make sure I've got this right: The upload function is being called on your parameters passed by your route, req and res. You set the shoe var from req.shoe. What are the chances that upload() is messing with your req? Drop a console.log(req) in right after you call upload and report back
How create channel to read a BLOB and write file system file
I am trying to create a image by fetching blob from MySQL DB ... Here goes the code.... var dbConn = DatabaseConnectionFactory.createDatabaseConnection('com.mysql.jdbc.Driver','jdbc:mysql://localhost:3306/dbname','username',''); var query_code = "Select blob from tblname where id =59"; // var result = dbConn.executeCachedQuery(query_code); dbConn.close(); if (result.next()) { var image=FileUtil.encode(result.getBytes(1)); $gc('image1', image); } Could anyone help me out to achieve this...
Did You receive any error with this code if so post it. Im not sure with Mirth connect tool But as far as I know, Retrieving the BLOB image from the DB directly with any IDE/Tools is always possible but difficult with 2 ways By encoding to BASE-64 charcter By specifying the entire location saving it locally. And try removing the dbconn.close(); do not use it or use it after if() statement. Because it will throw an error like "no statements were executed after dbconn.close();