瀏覽器/小程序 直傳圖片至minIO(私有OSS)

先上預(yù)覽


小程序上傳預(yù)覽

先說(shuō)WEB端(不論P(yáng)C還是H5)

1、前端自己簽名(不安全,不推薦)

  • web端因?yàn)樗写a 都會(huì)暴露給用戶,所有有密鑰泄露的風(fēng)險(xiǎn)。
  • 小程序端,雖然在微信客戶端黑盒執(zhí)行,但是引入 minIO 包后 小程序體積直線上升,也不好。
// 簽名方法
function signUrl(filePath) {
  // minIO 配置
  var minioClient = new Minio.Client({
    endPoint: 'xx.xx.xx.xx',
    port: xxxx,
    useSSL: false,
    accessKey: 'xxxxx',
    secretKey: 'xxxxx',
    bucketName: 'xxxxx'
  });
  return new Promise((resolve, reject) => {
    let bucketName = 'house'
    var policy = minioClient.newPostPolicy()
    policy.setBucket(bucketName)
    policy.setKey(filePath)
    var expires = new Date
    expires.setSeconds(24 * 60 * 60 * 10);
    policy.setExpires(expires)
    minioClient.presignedPostPolicy(policy, function (err, data) {
      if (err) return console.log(err)
      resolve(data)
    })
  })
}

2、拿到簽名后上傳

async function upload(file) {
    // file 為瀏覽器 input 選擇的 file對(duì)象
    let fileName = file.name; 
    let d = new Date();
    // 設(shè)置后的文件路徑,其實(shí)本質(zhì)是沒(méi)有路徑的,只是通過(guò)/來(lái)分割文件夾層級(jí)
    let filePath = `${d.getFullYear()}/${d.getMonth() + 1}/${d.getDate()}/${d.getTime()}-${fileName}`;
    // 獲取簽名
    let uploadInfo = await signUrl(filePath);

    let data = new FormData();
    for (const key in uploadInfo.formData) {
      if (Object.hasOwnProperty.call(uploadInfo.formData, key)) {
        const element = uploadInfo.formData[key];
        data.append(key, element)
      }
    }
    data.append('file', file)
    await axios.post(uploadInfo.postURL, data, {
      headers: { 'Content-Type': 'multipart/form-data' },
    }).catch(err=>{
      console.log(err)
    })
    // minIO 服務(wù)器 響應(yīng)結(jié)果為空,判斷是否成功 用HTTP狀態(tài)碼即可。
    // 這里返回的狀態(tài)碼 是204 但是文件確實(shí)已經(jīng)上傳成功了,所以上面代碼 加了catch捕獲異常
    // 直接返回 剛才拼接的 文件路徑。  前綴拼上 域名/IP+桶名+filePath 訪問(wèn)。
    return filePath;
  },

小程序端

這里使用后端簽名,后端使用nodeJS 代碼和瀏覽器自簽 幾乎 一模一樣
// 記得先安裝這些個(gè)依賴
var Minio = require('minio')
const express = require('express')
// 用 express 起個(gè)web服務(wù)
const app = express()
app.use(express.json()) // for parsing application/json
app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded
const port = 3000

app.post('/makeUploadUrl', (req, res) => {
    console.log(req.body);
     
    var minioClient = new Minio.Client({
        endPoint: 'xx.xx.xx.xx',
        port: xxxx,
        useSSL: false,
        accessKey: 'xxxx',
        secretKey: 'xxxx',
        bucketName: 'xxxx'
    });

   
    let bucketName = 'xxxx'
    var policy = minioClient.newPostPolicy()
    policy.setBucket(bucketName)
    policy.setKey(req.body.filePath)
    var expires = new Date
    // 過(guò)期時(shí)間
    expires.setSeconds(24 * 60 * 60 * 10);
    policy.setExpires(expires)
    minioClient.presignedPostPolicy(policy, function(err, data) {
      if (err) return console.log(err)
      res.json(data)
    })

})
app.listen(port, () => console.log(`minio app listening on port ${port}!`))
小程序端獲取簽名并上傳
// 從服務(wù)器獲取簽名
function getSign(filePath) {
    return new Promise((resolve, reject) => {
        uni.request({
            url: "http://127.0.0.1:3000/makeUploadUrl",
            method: "POST",
            data: {
                filePath
            },
            success(res) {
                console.log(res);

                resolve(res.data)
            }
        })

    })
}
// 發(fā)送上傳請(qǐng)求
function putImg(putObj, file) {
    return new Promise((resolve, reject) => {
        // 和web端的區(qū)別是 這里的file是 小程序獲取的圖片臨時(shí)地址,而不是file對(duì)象
        // 這里用的 uni-app 框架 ,如果用的 微信原生小程序開(kāi)發(fā)的 改成 wx.uploadFile 即可
        uni.uploadFile({
            url: putObj.postURL,
            filePath:file,
            name:'file',
            formData:{
                ...putObj.formData
            },
            header: {
                "content-type": "multipart/form-data"
            },
            success: (res) => {
                // console.log(res)
                resolve()
            },
            fail(err) {
                // console.log(err)
                reject(err)
            }
        })

    })

}
export default {
    async upload(file) {
        let fileName = file.split("/")[file.split("/").length - 1];
        let d = new Date();
        let filePath = `${d.getFullYear()}/${d.getMonth() + 1}/${d.getDate()}/${d.getTime()}-${fileName}`;
        let putObj = await getSign(filePath);
        await putImg(putObj, file)
        return filePath
    },


}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容