From 323f326716e90d255d90568cba817271479213c5 Mon Sep 17 00:00:00 2001 From: MrBBot Date: Sun, 14 Aug 2022 09:28:41 +0100 Subject: [PATCH] fix(File): respect typed array `byteOffset` and `byteLength` (#1601) `File` ignored the `byteOffset` and `byteLength` properties of typed arrays, meaning the entire backing `ArrayBuffer` was included. Notably, this caused issues when passing `Buffer`s to the `File` constructor. --- lib/fetch/file.js | 4 +++- test/fetch/file.js | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/lib/fetch/file.js b/lib/fetch/file.js index 647fc5ff38e..be12fb2b584 100644 --- a/lib/fetch/file.js +++ b/lib/fetch/file.js @@ -278,7 +278,9 @@ function processBlobParts (parts, options) { if (!element.buffer) { // ArrayBuffer bytes.push(new Uint8Array(element)) } else { - bytes.push(element.buffer) + bytes.push( + new Uint8Array(element.buffer, element.byteOffset, element.byteLength) + ) } } else if (isBlobLike(element)) { // 3. If element is a Blob, append the bytes it represents diff --git a/test/fetch/file.js b/test/fetch/file.js index 88e6636ece1..59015413eb0 100644 --- a/test/fetch/file.js +++ b/test/fetch/file.js @@ -120,6 +120,16 @@ test('File.prototype.text', async (t) => { t.equal(await file.text(), 'hello world') t.end() }) + + t.test('With TypedArray range', async (t) => { + const uint8_1 = new Uint8Array(Buffer.from('hello world')) + const uint8_2 = new Uint8Array(uint8_1.buffer, 1, 4) + + const file = new File([uint8_2], 'hello_world.txt') + + t.equal(await file.text(), 'ello') + t.end() + }) /* eslint-enable camelcase */ t.test('With ArrayBuffer', async (t) => { @@ -140,6 +150,15 @@ test('File.prototype.text', async (t) => { t.end() }) + t.test('With Buffer', async (t) => { + const buffer = Buffer.from('hello world') + + const file = new File([buffer], 'hello_world.txt') + + t.equal(await file.text(), 'hello world') + t.end() + }) + t.test('Mixed', async (t) => { const blob = new Blob(['Hello, ']) const uint8 = new Uint8Array(Buffer.from('world! This'))