13

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- 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- 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!

jaimefps
  • 2,244
  • 8
  • 22
  • 45

1 Answers1

24

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

Rahadian Kumang
  • 591
  • 6
  • 15
  • wow, I was not expecting something as simple as `.byteSize`. Thanks! – jaimefps Oct 26 '17 at 17:00
  • `Buffer.byteLength(myFileBuffer)` is what I see for the current node docs, though I'm sure this was accurate when you posted it. link is also broken now. I think `myBuffer.length` is more ideal than `myBuffer.data.toString().length` because it avoids converting the `Buffer` to string. Similarly to when this solution was posted, `Buffer.byteLength(myFileBuffer)` and `myBuffer.length` are essentially the same thing – Rikki Schulte Nov 29 '21 at 09:29