如何在 JavaScript 中获取缓冲图像的大小(以字节为单位)?我不允许信任客户端的文件大小,并且需要在后端进行验证作为上传验证的一部分。我的设置如下:
1-我在客户端上传一个文件并将其从 React 组件发送到 Node:
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 中的数据作为对象接收:
{
file: {
name: 'test',
data: <Buffer 12 50 4e ... >,
encoding: '7bit',
mimetype: 'image/png',
}
}
如何测量缓冲区的字节大小?提前致谢!
就像是file.data.byteLength
or file.data.toString().length
将返回尺寸byte
,除以 1024 即可得到大小kb
https://nodejs.org/api/buffer.html#buffer_class_method_buffer_bytelength_string_encoding https://nodejs.org/api/buffer.html#buffer_class_method_buffer_bytelength_string_encoding
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)