@lacussoft/to-arraybuffer
TypeScript icon, indicating that this package has built-in type declarations

1.2.1 • Public • Published

LacusSoft :: file2arraybuffer

NPM Latest Version Downloads Count Bundle Size Last Update Date Project License

Promise based function to generate ArrayBuffer objects for files - commonly required by web services like the SharePoint REST API.

Browser Support

Chrome Firefox Safari Opera Edge IE
Latest Latest Latest Latest Latest 11

Installation

$ npm install file2arraybuffer

Import

// ES Modules
import fileToArrayBuffer from 'file2arraybuffer'

// Common JS
const fileToArrayBuffer = require('file2arraybuffer')

or import it through your HTML file, using CDN:

<script src="https://cdn.jsdelivr.net/npm/file2arraybuffer@latest/dist/to-arraybuffer.min.js"></script>

NOTE: when used as UMD, global function will be available as fileToArrayBuffer ("To", not "2").

Usage

You can use various parameter types to reference your HTML input element holding the file, as well as Blob instances you may generate on the fly. As the process of generating ArrayBuffer is computationally expense, the result is not the ArrayBuffer itself, but a promise to it, so consider asynchronous approach to work with that.

<input id="attachment" type="file"  />
<script type="text/javascript">

    const inputEl = document.getElementById("attachment")
    inputEl.addEventListener('change', async (ev) => {

        // Use a query selector directly
        const arrBuffer = await fileToArrayBuffer('#attachment')

        // Use the HTML element directly (must be of type "file")
        const arrBuffer = await fileToArrayBuffer(ev.target)

        // Use the element attribute that stores the FileList (only the first one will be converted)
        const arrBuffer = await fileToArrayBuffer(ev.target.files)

        // Use the element specific file within the FileList (great if you have a multi-file input)
        const arrBuffer = await fileToArrayBuffer(ev.target.files[0])

        /* do stuff */
    })

    // or if you got a Blob object
    const myBlob = new Blob(['Hello, world'], { type: 'text/plain' })
    fileToArrayBuffer(myBlob).then((arrBuffer) => /* do stuff */)

</script>

However, keep in mind that the function handles one single file, so by referencing an HTMLInputElement or its FileList attribute will only generate the ArrayBuffer for the el.files[0]. If you are working with multi-file input, you must iterate over the FileList object.

<input id="attachments" type="file" multiple="true" />
<script type="text/javascript">

    const input = document.getElementById("attachments")
    const promises = Array.from(input.files).map(fileToArrayBuffer)

    Promise.all(promises).then((arrBuffers) => {
        /* do stuff */
    })

</script>

Package Sidebar

Install

npm i @lacussoft/to-arraybuffer

Weekly Downloads

0

Version

1.2.1

License

MIT

Unpacked Size

18.7 kB

Total Files

9

Last publish

Collaborators

  • juliolmuller