代码之家  ›  专栏  ›  技术社区  ›  jaimefps

缓冲区的字节大小(Javascript/节点)[重复]

  •  11
  • jaimefps  · 技术社区  · 8 年前

    如何在javascript中获得缓冲图像的大小(以字节为单位)?我不允许在客户端信任文件大小,需要在后端进行验证,作为上传验证的一部分。我的设置如下:

    1-我在客户端上传一个文件,并将其从React组件发送到节点:

          fileUpload() {
              const url = '/.../...'
              const formData = new FormData()
              formData.append('file', this.state.file)
              formData.append('actualSize', this.state.file.size) //not allowed to use this.
              const config = { headers: { 'content-type': 'multipart/form-data' } }
              axios.post(url, formData, config)
          }
    

    2-使用一些中间件,我将节点中的数据作为对象接收:

      { 
          file: { 
                name: 'test',
                data: <Buffer 12 50 4e ... >,
                encoding: '7bit',
                mimetype: 'image/png',
          } 
      }
    

    如何测量缓冲区的字节大小?提前感谢!

    1 回复  |  直到 8 年前
        1
  •  21
  •   Rahadian Kumang    8 年前

    类似于 file.data.byteLength 或 file.data.toString().length byte ,除以1024得到大小 kb

    https://nodejs.org/api/buffer.html#buffer_class_method_buffer_bytelength_string_encoding

    推荐文章