From 480a00872bc7bf6c78d1bfb8b18d56ecf8472011 Mon Sep 17 00:00:00 2001 From: fatelei Date: Tue, 30 May 2023 13:15:12 +0800 Subject: [PATCH] fix: fetching files renders invalid blob Signed-off-by: fatelei --- README.md | 8 ++++++++ src/index.mjs | 5 ++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 33df12d..4e76290 100644 --- a/README.md +++ b/README.md @@ -121,6 +121,13 @@ fetch('/bear', { open(r.headers.get('location')); return r.json(); }) + +// fetch image +fetch('https://i.imgur.com/4AiXzf8.jpg', { + responseType: 'blob' +}).then( r => { + return r.blob(); +}) ``` * * * @@ -140,6 +147,7 @@ Unfetch will account for the following properties in `options`: * `headers`: An `Object` containing additional information to be sent with the request, e.g. `{ 'Content-Type': 'application/json' }` to indicate a JSON-typed request body. * `credentials`: ⚠ Accepts a `"include"` string, which will allow both CORS and same origin requests to work with cookies. As pointed in the ['Caveats' section](#caveats), Unfetch won't send or receive cookies otherwise. The `"same-origin"` value is not supported. ⚠ * `body`: The content to be transmitted in request's body. Common content types include `FormData`, `JSON`, `Blob`, `ArrayBuffer` or plain text. + * `responseType`: An enumerated string value specifying the [type](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseType) of data contained in the response, the default value of text is used. ### `response` Methods and Attributes These methods are used to handle the response accordingly in your Promise chain. Instead of implementing full spec-compliant [Response Class](https://fetch.spec.whatwg.org/#response-class) functionality, Unfetch provides the following methods and attributes: diff --git a/src/index.mjs b/src/index.mjs index 20a2021..f2f6b3c 100644 --- a/src/index.mjs +++ b/src/index.mjs @@ -2,6 +2,9 @@ export default function (url, options) { options = options || {}; return new Promise((resolve, reject) => { const request = new XMLHttpRequest(); + if (options.responseType) { + request.responseType = options.responseType; + } const keys = []; const headers = {}; @@ -12,7 +15,7 @@ export default function (url, options) { url: request.responseURL, text: () => Promise.resolve(request.responseText), json: () => Promise.resolve(request.responseText).then(JSON.parse), - blob: () => Promise.resolve(new Blob([request.response])), + blob: () => Promise.resolve(new Blob([request.response], {type: request.response.type})), clone: response, headers: { keys: () => keys,