ITPub博客

首页 > IT职业 > IT职场 > 用JavaScript来上传二进制文件到Azure Blob

用JavaScript来上传二进制文件到Azure Blob

IT职场 作者:yxl1108 时间:2021-09-09 09:10:54 0 删除 编辑

需求:用浏览器来上传二进制文件到Azure Blob

JavaScript 语言自身只有字符串数据类型,没有二进制数据类型。

上传文件到Azure Blob有四个API:

createBlockBlobFromBrowserFile(container, blob, browserFile [, options], callback)

createBlockBlobFromLocalFile(container, blob, localFileName [, options], callback)

createBlockBlobFromStream(container, blob, (Stream), streamLength [, options], callback)

createBlockBlobFromText(container, blob, text [, options], callback)

从本地文件上传,需要用到node的ps文件操作,用file控件只能上传input-file,而我需要把拿到的base64文件转成二进制流才行

解决方案:Buffer

在处理像TCP流或文件流时,必须使用到二进制数据。因此在 Node.js中,定义了一个 Buffer 类,该类用来创建一个专门存放二进制数据的缓存区。

npm也提供了一个Buffer,和node API基本一致

npm install buffer

在vue组件中引入

var Buffer = require('buffer/').Buffer

最终:

  uploadAzure () {
      // const self = this
      let resu = new Promise(async (resolve, reject) => {
        /* eslint-disable no-undef */
        let rawdata = Session.get('img_base64')
        let matches = rawdata.match(/^data:([A-Za-z-+/]+);base64,(.+)$/)
        let type = matches[1]
        let buffer = new Buffer(matches[2], 'base64')
        let blobUri = Config.azure.host

        let imageid = Util.uuid() + '.jpg'

        try {
          let res = await Api.get(Session.get('SID'), 'azure/storagesas', {imageid: imageid})
          if (res.code === 0) {
            let sasKey = res.data.token
            console.log(sasKey)
            let blobService = AzureStorage.Blob.createBlobServiceWithSas(blobUri, sasKey).withFilter(new AzureStorage.Blob.ExponentialRetryPolicyFilter())
            blobService.createBlockBlobFromText(Config.azure.container, imageid, buffer, {contentType: type}, function (error, result, response) {
              if (!error) {
                resolve(result)
              }
            })
          }
        } catch (e) {
          console.log(e)
        }
      })

      resu.then((res) => {
        console.log(res.name)
        Session.set('imageid', res.name)
      })
    },

图片描述

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/3158/viewspace-2808378/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-30

  • 博文量
    82
  • 访问量
    492