小程序 · 2019年9月1日 0

浏览器/小程序 直传图片至minIO(私有OSS)

先上预览

小程序上传预览

先说WEB端(不论PC还是H5)

1、前端自己签名(不安全,不推荐)

  • web端因为所有代码 都会暴露给用户,所有有密钥泄露的风险。
  • 小程序端,虽然在微信客户端黑盒执行,但是引入 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对象
    let fileName = file.name; 
    let d = new Date();
    // 设置后的文件路径,其实本质是没有路径的,只是通过/来分割文件夹层级
    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 服务器 响应结果为空,判断是否成功 用HTTP状态码即可。
    // 这里返回的状态码 是204 但是文件确实已经上传成功了,所以上面代码 加了catch捕获异常
    // 直接返回 刚才拼接的 文件路径。  前缀拼上 域名/IP+桶名+filePath 访问。
    return filePath;
  },

小程序端

这里使用后端签名,后端使用nodeJS 代码和浏览器自签 几乎 一模一样
// 记得先安装这些个依赖
var Minio = require('minio')
const express = require('express')
// 用 express 起个web服务
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
    // 过期时间
    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}!`))

小程序端获取签名并上传

// 从服务器获取签名
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)
            }
        })
    })
}
// 发送上传请求
function putImg(putObj, file) {
    return new Promise((resolve, reject) => {
        // 和web端的区别是 这里的file是 小程序获取的图片临时地址,而不是file对象
        // 这里用的 uni-app 框架 ,如果用的 微信原生小程序开发的 改成 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
    },
}