Skip to content

Handling blob response type #3484

@l-vincent-l

Description

@l-vincent-l

I'm trying to use this extension https://medium.com/@martin.mohnhaupt/an-htmx-file-download-extension-cccfaba5e2e2, but has pointed out at the end of the article it only works if the data sent is base64.

I tried to bypass this, by adding a hook a set the responsetype

htmx.defineExtension('htmx-download', {
   onEvent: function (name, evt) {
      if (name == 'htmx:beforeSend') {
         evt.xhr.responseType = 'blob';
      }
      if (name == 'htmx:beforeSwap') {
         const status = evt.detail.xhr.status;
         if (status == 200) {
            const xhr = evt.detail.xhr;
            const re_filename = /filename[^;=\n]*=((['"])?(.*)\2|[^;\n]*)/;
            const content_disposition = xhr.getResponseHeader('content-disposition');
            const matches = content_disposition ? re_filename.exec(content_disposition) : null;
            const filename = matches && matches[3] ? matches[3] : 'download';

            // Prepare a link element for a file download
            const link = document.createElement("a");
            link.style.display = "none";
            link.href = URL.createObjectURL(response);
            link.download = filename;

            link.click();
            URL.revokeObjectURL(link.href);
         }
      }
      return true;
   },
})

It now downloads the flie but then I have swapError even if I have hx-swap="none".
Do you know how can I convert the response if it's text ? Or how can I avoid the swap?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions