How to get an image from queued request body (Workbox PWA)

98 views Asked by At

I am using Workbox in my PWA. If app is offline and image posting request fails - it is automatically added to IndexedDB.

    const post = (file: File) => {
        const formData = new FormData()
        formData.append("image", file);
        axios.post('http://some.com/upload', formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        }).then(...)

I want to show user all images of queued requests in offline mode. How i get requests:

import { openDB } from 'idb';
const db = await openDB('workbox-background-sync');
const queuedRequests = await db.getAllFromIndex('requests', 'queueName');

Body of request is ArrayBuffer (how request is stored in IndexedDB is showed on the picture). I don't understand how to "extract" image and pass it to createObjectURL( imageBlob ).

If i decode body like this:

let view = new Uint8Array(body);
let bodyAsString = new TextDecoder().decode(view);

I got post body which contains image bytes after "image/png\r\n\r\n":

------WebKitFormBoundaryfc7IW9qvYqE2SdSm\r\nContent-Disposition: form-data; name="image"; filename="1.png"\r\nContent-Type: image/png\r\n\r\n�PNG\r\n\x1A\n\x00\...

I don't think that parsing payload using regexp, then encoding it is a good approach. How can this be done?

0

There are 0 answers