缓冲区的字节大小(JavaScript/节点) [英] byte size of buffer (Javascript / Node)

查看:62
本文介绍了缓冲区的字节大小(JavaScript/节点)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I get the size (in bytes) of a bufferd image in javascript? I am not allowed to trust the file size in the client side, and need to verify in the backend as part of upload validation. My setup is as follows:

1-我将文件上传到客户端,然后从React组件发送到Node:

1- I upload a file in the client and send it to Node from a React component:

      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-使用一些中间件,我将Node中的数据作为对象接收:

2- Using some middleware, I receive the data in Node as an object:

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

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

How can I measure the byte size of the buffer? Thanks in advance!

推荐答案

类似于 file.data.byteLength file.data.toString().length 的东西会返回以 byte 为单位的大小,除以1024得到以 kb

something like file.data.byteLength or file.data.toString().length will return the size in byte, divide with 1024 to get the size in kb

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

这篇关于缓冲区的字节大小(JavaScript/节点)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆