1.1.0 • Published 3 years ago

@bytesoftio/helpers-input v1.1.0

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

@bytesoftio/helpers-input

Installation

yarn add @bytesoftio/helpers-input or npm install @bytesoftio/helpers-input

Table of contents

Description

This package provides several helpers to deal with file inputs.

Examples

Submit a file to the server

Submit a file immediately after selecting one.

import { selectFile } from "@bytesoftio/helpers-input"
import axios from "axios"

const handleSelectFile = async () => {
  const file = await selectFile()
  
  if ( ! file) return

  submitFile(file) 
}

const submitFile = async (file: File) => {
  const formData = new FormData()
  formData.append('file', file)

  await axios.post(`/endpoint`, formData, {
    headers: { 'content-type': 'multipart/form-data' },
  })
}


<button onClick={handleSelectFile}/>

Show a file preview

Show a file preview immediately after selection.

import { selectFileOfType } from "@bytesoftio/helpers-input"

const handleSelectFileOfType = async () => {
  const file = await selectFileOfType('image/*')

  if ( ! file) return

  showPreview(file)
}

const showPreview = (file: File) => {
  const img = document.createElement('img')
  img.src = URL.createObjectURL(file)
  document.body.appendChild(img)
}

<button onClick={handleSelectFileOfType}/>

Usage

selectFile

Let the user select a single file.

import { selectFile } from "@bytesoftio/helpers-input"
import axios from "axios"

const handleSelectFile = async () => {
  const file = await selectFile()
  
  if ( ! file) return

  // do something with the file...
}

<button onClick={handleSelectFile}/>

selectFiles

Similar to selectFile, but allows user to select multiple files.

import { selectFiles } from "@bytesoftio/helpers-input"

const handleSelectFiles = async () => {
  const files = await selectFiles()

  if ( ! files) return

  // do something with the files...
}

<button onClick={handleSelectFiles}/>

selectFileOfType

Allow only specific types of files, used inputs accept property behind the scenes, see here.

import { selectFileOfType } from "@bytesoftio/helpers-input"

const handleSelectFileOfType = async () => {
  const file = await selectFileOfType('image/*')

  if ( ! file) return

  // do something with the file...
}

<button onClick={handleSelectFileOfType}/>

selectFilesOfType

Similar to selectFileOfType, but allows user to select multiple files.

import { selectFilesOfType } from "@bytesoftio/helpers-input"

const handleSelectFilesOfType = async () => {
  const files = await selectFilesOfType('image/*')

  if ( ! files) return

  // do something with the files...
}

<button onClick={handleSelectFilesOfType}/>