So I'm creating a ticket system, and what I'd like to do is to add any type of file to my tickets and store them in my database. So I was thinking about using a noSQL database just for the "file part". But what would be the best way to set up my database? For example if I have to do a database schema, what are the fields that would have to be in the database, to be able to store all the files I want (PDF, JPG, JPEG.....)
CodePudding user response:
You can embed files inside json document in mongoDB with known limit of 16MB. For files above 16MB you can use the gridFS specification. But in general the best practice approach is to store references in the mongoDB JSON document and store the files in external specialized file object storage like S3 ...
CodePudding user response:
If you want to upload files above 16MB you can use gridFs.
METHOD 1
Other than that if you want to store file like PDF or Images you can use base64 strings. Then you can store your file as a string in the database.
Please find my code below and try it here. You can find out how to generate the base64 string and how we can view it in our browser.
<!DOCTYPE html>
<html>
<head>
<title>Convert to Base64</title>
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
</head>
<body>
<H1>Select file to upload and convert into base64 string</H1>
<hr>
<br>
<label for="fileUpload">Choose file:</label>
<input type="file" id="fileUpload" name="fileUpload" />
<br><br>
<button id="jsonConvert">Convert into Base64</button>
<img style='display:block; width:100px;height:100px;' id='base64image' src='' />
<iframe id='base64pdf' width='100%' height='100%' src=''>
</iframe>
</body>
</html>
<script type="text/javascript">
const toBase64 = file => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
$('#jsonConvert').click(function () {
const uploadedFile = document.querySelector('#fileUpload').files[0];
toBase64(uploadedFile)
.then(res => {
const filetype = res.split("/")[0];
if (filetype == "data:application") {
document.getElementById('base64pdf').src = res;
} else if (filetype == "data:image") {
document.getElementById('base64image').src = res;
}
console.log(res);
})
.catch(err => {
console.log(err);
})
});
</script>
METHOD 2
You can upload your file to a storage bucket like S3 bucket and get the link of it and store that link in your database. Using that link you can view it.
Hope you will find a solution from above methods.