所以我正在創建一個票證系統,我想做的是將任何型別的檔案添加到我的票證并將它們存盤在我的資料庫中。因此,我正在考慮僅將 noSQL 資料庫用于“檔案部分”。但是設定我的資料庫的最佳方法是什么?例如,如果我必須做一個資料庫模式,資料庫中必須有哪些欄位才能存盤我想要的所有檔案(PDF、JPG、JPEG .....)
uj5u.com熱心網友回復:
您可以在 mongoDB 的 json 檔案中嵌入檔案,已知限制為 16MB。對于 16MB 以上的檔案,您可以使用gridFS規范。但總的來說,最佳實踐方法是將參考存盤在 mongoDB JSON 檔案中,并將檔案存盤在外部專用檔案物件存盤中,如 S3 ...
uj5u.com熱心網友回復:
如果要上傳 16MB 以上的檔案,可以使用gridFs。
方法一
除此之外,如果您想存盤 PDF 或影像等檔案,您可以使用base64 字串。然后,您可以將檔案作為字串存盤在資料庫中。
請在下面找到我的代碼并在此處嘗試。您可以了解如何生成 base64 字串以及我們如何在瀏覽器中查看它。(如果此代碼在此處不起作用(PDF 部分),請復制代碼并在本地計算機上運行)
<!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>
方法二
您可以將檔案上傳到 S3 存盤桶等存盤桶,并獲取它的鏈接并將該鏈接存盤在您的資料庫中。使用該鏈接,您可以查看它。
希望您能從上述方法中找到解決方案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/477732.html
