在試用網(wǎng)站做推廣網(wǎng)站運(yùn)營(yíng)
minio官方文檔
minio-js可以支持ts。
安裝完可能會(huì)出現(xiàn)
Can‘t import the named export ‘xxx‘ from non EcmaScript module (only default export is available)
可以嘗試降低minio的版本
npm install minio@7.0.18 --save
代碼:
初始化
const Minio = require('minio')const minioClient = new Minio.Client({endPoint: '192.l68.0.1', //minio服務(wù)器ip,不能加http://port: 9000,accessKey: 'xxxx', //usernamesecretKey: 'xxxx', //passworduseSSL: false //https訪問需要設(shè)置為true
})
上傳文件
const stream = require('stream')/**** @export 上傳文件(stream流方法)* @param {*} backetName String 存儲(chǔ)桶名字* @param {*} fileObj Object 文件對(duì)象* @param {*} callback function 回調(diào)函數(shù)*/
export function uploadFile (backetName, fileObj, callback) {console.log(backetName, fileObj)if (fileObj) {const file = fileObjif (file === undefined) {// 未選擇} else {const date = new Date()const year = new Date().getFullYear()const month =date.getMonth() + 1 < 10? '0' + (date.getMonth() + 1): date.getMonth() + 1const day = date.getDate() > 9 ? date.getDate() : '0' + date.getDate()const fileName = date.getTime() + file.nameconst fileDate = '' + year + month + dayconst mineType = file.typeconst fileSize = file.sizeconsole.log('fileName', fileName)// 參數(shù)const metadata = {'content-type': mineType,'content-length': fileSize}// 判斷儲(chǔ)存桶是否存在minioClient.bucketExists(backetName, function (err) {console.log('判斷儲(chǔ)存桶是否存在')if (err) {if (err.code === 'NoSuchBucket') {return console.log('bucket does not exist.')}console.log('1233221')return console.log(err)}// 準(zhǔn)備上傳const reader = new FileReader()reader.readAsDataURL(file)reader.onloadend = function (e) {const dataurl = e.target.resultconst blob = toBlob(dataurl)const reader2 = new FileReader()reader2.readAsArrayBuffer(blob)reader2.onload = function (ex) {const bufferStream = new stream.PassThrough()bufferStream.end(Buffer.from(ex.target.result))minioClient.putObject(backetName,`${fileDate}/${fileName}`,bufferStream,fileSize,metadata,(err) => {if (err == null) {minioClient.presignedPutObject(backetName,`${fileDate}/${fileName}`,24 * 60 * 60,function (err1, presignedUrl) {console.log(err1)if (err1) returnif (presignedUrl) {const arr = presignedUrl.split('?')if (arr.length === 2) {callback(arr[0])}}})}})}}})}}
}/**** @export base64轉(zhuǎn)blob* @param {*} base64Data Object base64數(shù)據(jù)* @return {*} blob*/
export function toBlob (base64Data) {let byteString = base64Dataif (base64Data.split(',')[0].indexOf('base64') >= 0) {byteString = window.atob(base64Data.split(',')[1]) // base64 解碼} else {byteString = unescape(base64Data.split(',')[1])}// 獲取文件類型const mimeString = base64Data.split(';')[0].split(':')[1] // mime類型const uintArr = new Uint8Array(byteString.length) // 創(chuàng)建視圖for (let i = 0; i < byteString.length; i++) {uintArr[i] = byteString.charCodeAt(i)}const blob = new Blob([uintArr], {type: mimeString})return blob
}// 先判斷桶是否存在,如果可確保捅已經(jīng)存在,則直接調(diào)用uploadFile方法
export function checkedAndUpload (bucketName, info, callback) {minioClient.bucketExists(bucketName, err => {if (err) {minioClient.makeBucket(bucketName, 'us-east-1', err1 => {if (err1) {console.error(`${info.file.name}文件上傳失敗`)return}uploadFile(bucketName, info, callback)})} else {uploadFile(bucketName, info, callback)}})
}// 先判斷桶是否存在
export function connectionStatus (bucketName, callback) {minioClient.bucketExists(bucketName, err => {console.Log(err)callback(err)})
}
上傳文件簡(jiǎn)單版:
const bucketName = 'picturebook-version'; // 替換為你的存儲(chǔ)桶名稱
const objectName = file.file.name; // 使用文件名作為對(duì)象名稱//創(chuàng)建 FileReader 對(duì)象
const reader = new FileReader();// 當(dāng)讀取完成時(shí)觸發(fā)的回調(diào)函數(shù)
reader.onload = (event) => {// 從事件對(duì)象中獲取文件內(nèi)容const fileContent = event.target.result;// 轉(zhuǎn)換 ArrayBuffer 為 Buffer 類型數(shù)據(jù)const buffer = Buffer.from(fileContent);// 使用 putObject 方法上傳文件內(nèi)容this.minioClient.putObject(bucketName, objectName, buffer, buffer.length, (err, etag) => {if (err) {console.error('上傳文件失敗:', err);} else {this.fileList.push(this.newFile);this.fileName = objectName;console.log('文件上傳成功,ETag:', etag);}});
};// 開始讀取文件
reader.readAsArrayBuffer(file.file);
下載文件
export function downloadFile (bucketName, fileName, callback) {minioClient.getObject(bucketName, fileName, (err, dataStream) => {callback(err, dataStream)})
}
使用
<div @click="selectFile" style="cursor: pointer; width: 80px; text-align: right"class="ant-upload-text" > 上傳 </div>
<input type="file id="uploadInput" ref="uploadInput" v-show="false" @change="changeInput()"/>
import { uploadFile } from '@/utils/minio'selectFile() {const inputDOM = this.$refs.uploadInputinputDOM.click()
},
changeInput() {const file = this.$refs.uploadInput.filesif (file.length) {this.sourceFile = {name: file[0].name,size: file[0].size,type: file[0].type,}uploadFile('carbon', file[0], (e) => {this.$refs.uploadInput.value = ''this.sourceFile = {...this.sourceFile,url: e,}})}
},
拓展
優(yōu)點(diǎn):
1.直接訪問對(duì)象存儲(chǔ):前端直接與 MinIO 通信,而不需要通過后端服務(wù)器作為中介。這樣可以降低后端服務(wù)器的負(fù)擔(dān),減少網(wǎng)絡(luò)傳輸時(shí)間,提高文件傳輸效率。
2.降低后端開發(fā)成本:前端直接使用 MinIO SDK 進(jìn)行文件上傳和下載,減少了與后端開發(fā)相關(guān)的工作量。這樣可以加快開發(fā)速度,并降低了整體的開發(fā)成本。
3.分布式存儲(chǔ)支持:MinIO 支持分布式存儲(chǔ),可以在多個(gè)節(jié)點(diǎn)之間存儲(chǔ)數(shù)據(jù),實(shí)現(xiàn)高可用性和容錯(cuò)性。前端直接與 MinIO 通信,可以利用 MinIO 的分布式特性,將文件分散存儲(chǔ)在不同的節(jié)點(diǎn)上,提高文件的可靠性和可用性。
4.快速上傳和下載:MinIO 針對(duì)文件上傳和下載進(jìn)行了優(yōu)化,提供了快速的傳輸速度和低延遲的訪問體驗(yàn)。前端直接與 MinIO 通信,可以獲得更快的上傳和下載速度,提高用戶體驗(yàn)。
5.可控性和安全性:前端直接使用 MinIO SDK 進(jìn)行文件上傳和下載,可以根據(jù)需要設(shè)置訪問權(quán)限、加密方式等安全措施,保護(hù)文件的安全性和完整性。同時(shí),前端可以完全掌控文件的訪問和管理,保留對(duì)文件的完全控制權(quán)。
6.跨平臺(tái)兼容性:MinIO 提供了豐富的客戶端 SDK,包括 JavaScript SDK,在各種前端平臺(tái)(Web、移動(dòng)端、桌面端)上都可以方便地集成和使用。這樣可以實(shí)現(xiàn)跨平臺(tái)的文件上傳和下載,滿足不同平臺(tái)的需求。
缺點(diǎn):
1.只支持Webpack工程化構(gòu)建的項(xiàng)目,因?yàn)閣ebpack是基于nodeJs的,可以使用require, fs等函數(shù)
2.不支持Vite工程化構(gòu)建形式,Vite是EsModule純?yōu)g覽器模塊的形式,沒有nodeJs里的函數(shù),只能使用import,但部分第三方庫(kù)并不支持,會(huì)報(bào)奇怪的錯(cuò)誤
3.前端直傳Minio是無法獲取上傳進(jìn)度的,自然也就無法顯示進(jìn)度條,從而無法擁有良好的人機(jī)交互感,并且需要等待Minio反饋后才能判斷是否上傳成功
4.端口,登錄賬號(hào),登錄密碼都寫在前端,會(huì)暴露關(guān)鍵信息,易造成不必要的信息泄露,并且不易維護(hù)
5.由前端寫Minio接口不利于之后的擴(kuò)展,每開一個(gè)項(xiàng)目,都需要copy代碼,無形中增加了維護(hù)的困難性