🖼 Simple file-upload utility that shows a preview of the uploaded image. Written in TypeScript. No dependencies. Works well with or without a framework.

Overview

file-upload-with-preview

🖼 Simple file-upload utility that shows a preview of the uploaded image. Written in TypeScript. No dependencies. Works well with or without a framework.

NPM Version NPM Downloads License Tweet

Links

Install

yarn add file-upload-with-preview

Or, you can include it through the browser.

<link
  rel="stylesheet"
  type="text/css"
  href="https://unpkg.com/file-upload-with-preview/dist/file-upload-with-preview.min.css"
/>

<script src="https://unpkg.com/file-upload-with-preview/dist/file-upload-with-preview.iife.js"></script>

About

This is a simple frontend utility meant to help the file-upload process on your website.

It is written in pure JavaScript and has no dependencies. You can check out the live demo here.

For the most part, browsers do a good job of handling image-uploads. That being said - I find the ability to show our users a preview of their upload can go a long way in increasing the confidence in their upload.

file-upload-with-preview aims to address the issue of showing a preview of a user's uploaded image in a simple to use package.

Features

  • Shows the actual image preview in the case of a single uploaded .jpg, .jpeg, .gif, or .png image. Shows a success-image in the case of an uploaded .pdf file, uploaded video, or other un-renderable file - so the user knows their image was collected successfully. In the case of multiple selected files, the user's selected images will be shown in a grid.
  • Shows the image name in the input bar. Shows the count of selected images in the case of multiple selections within the same input.
  • Allows the user to clear their upload and clear individual images in the multiple grid
  • Looks great
  • Framework agnostic - to access the uploaded file/files just use the cachedFileArray (always will be an array) property of your FileUploadWithPreview object.
  • For every file-group you want just initialize another FileUploadWithPreview object with its own uniqueId - this way you can have multiple file-uploads on the same page. You also can just use a single input designated with a multiple property to allow multiple files on the same input.

Usage

This library looks for a specific HTML element to display the file-upload. Simply add the below div to your HTML. Make sure to populate your unique id in the data-upload-id attribute.

<div class="custom-file-container" data-upload-id="myFirstImage"></div>

Then, initialize your file-upload in the JavaScript like below:

import { FileUploadWithPreview } from 'file-upload-with-preview';
import 'file-upload-with-preview/dist/file-upload-with-preview.min.css';

const upload = new FileUploadWithPreview('myFirstImage');

If you're importing directly in the browser, use the following instead:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <link
      rel="stylesheet"
      type="text/css"
      href="https://unpkg.com/file-upload-with-preview/dist/file-upload-with-preview.min.css"
    />
  </head>
  <body>
    <div class="custom-file-container" data-upload-id="myFirstImage"></div>
    <script src="https://unpkg.com/file-upload-with-preview"></script>
  </body>
</html>

Then initialize like this:

const upload = new FileUploadWithPreview.FileUploadWithPreview('myFirstImage');

Then when you're ready to use the user's file for an API call or whatever, just access the user's uploaded file/files in the cachedFileArray property of your initialized object like this:

upload.cachedFileArray;

You can optionally trigger the image browser and clear selected images programmatically. There are additional methods on the class if you'd like to take a look at the source code.

upload.emulateInputSelection(); // to open image browser
upload.resetPreviewPanel(); // clear all selected images

You may also want to capture the event when an image is selected.

import { Events, ImageAddedEvent } from 'file-upload-with-preview';

window.addEventListener(Events.IMAGE_ADDED, (e: Event) => {
  const { detail } = e as unknown as ImageAddedEvent;

  console.log('detail', detail);
});

Note

The cachedFileArray property is always an array. So if you are only allowing the user to upload a single file, you can access that file at cachedFileArray[0] - otherwise just send the entire array to your backend to handle it normally.

Make sure to pass in multiple: true in your options if you want to allow the user to select multiple images.

Docs

View the full docs here.

Full Example

See the full example in the ./example/index.ts folder. See the top of this README for some links to a few live CodeSandbox's.

Browser Support

If you are supporting a browser like IE11, one way to add a polyfill for fetch and promise is by adding the following in the bottom of your index.html:

<script src="https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.auto.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/2.0.3/fetch.js"></script>

Development

# Install dependencies
yarn

# Watch changes during local development
yarn dev

# Run tests
yarn test

# Build library
yarn build

Other

Go ahead and fork the project! Submit an issue if needed. Have fun!

License

MIT

Comments
  • Only saving last image of multiple uploads

    Only saving last image of multiple uploads

    If multiple images are uploaded one at a time only the last image you upload will show up in Request.Files.

    Upload a three images by selecting them individually. You will see the previews in the preview window.

    When you check Request.Files it will only have the last image you uploaded not the previous two.

    opened by Nomad7788 11
  • Active Class and Select Image

    Active Class and Select Image

    During the use of this module, I required at least two additional features:

    • one is CSS class when image is loaded and the preview gets active
    • another one is an API to manually trigger image browser

    So in this PR, I try to implement two things myself at my convenient.

    Test was passed with no problem!

    opened by firstor 6
  • Multiple file input. Images still in $_FILES after deleting.

    Multiple file input. Images still in $_FILES after deleting.

    I have found bug probably. Case 1:

    • add 3 files one by one in multiple file input
    • delete 2 of them
    • save form
    • expected results: 1 record in database. Test passed

    Case 2:

    • add 3 files at the same time (using crtrl/cmnd button) in multiple file input
    • delete 2 of them
    • save form
    • expected results: 1 record in database. Actual: 3 records. Test FAILED

    Case 3:

    • add 3 files at the same time (using crtrl/cmnd button) in multiple file input
    • delete all of them
    • save form
    • expected results: 0 records in database. Test PASSED.

    Something is wrong here. Please let me know it is an issue and solve it or close this ticket if it is not

    opened by wwwAdik 5
  • Unable to Replace background image for image grid

    Unable to Replace background image for image grid

    I want to replace default base64 image with backgroundImage base64

    here is the script i use

       var upload = new FileUploadWithPreview('myUniqueUploadId', {
                maxFileCount: 4,
                text: {
                    chooseFile: 'Maximum 4 Images Allowed',
                    browse: 'Add More Images',
                    selectedCount: 'Files Added',
                },
                images: {
                    baseImage: backgroundImage,
                },
            })
    

    but it doesn't work, How do i display backgroundImage

    opened by sanoj26692 5
  • TypeError: FileUploadWithPreview is not a constructor

    TypeError: FileUploadWithPreview is not a constructor

    I had this script on my site, and now it stop working... Error i have is "TypeError: FileUploadWithPreview is not a constructor" Can You help it?

    opened by GrzegorzWalewski 5
  • There is no name attribute to get the image on backed

    There is no name attribute to get the image on backed

    Hi, I was using this utility to upload a profile image but there is no name attribute to get the image on backend (I am using codeigniter on backend). and when I did set it (name attribute) I was getting en empty array with no attributes (like size, name etc).

    opened by MdFarzan 4
  • presetFiles doesn't work with base64 encoded binary image string

    presetFiles doesn't work with base64 encoded binary image string

    Hi,

    I'm not sure if the option "presetFiles" only works with URL. But it didn't work when I tried to use data:image.

    This function provides a convenient way of serving images from your app that are not web-accessible (e.g., in public/).

    Cheers

    opened by oldcastlehq 4
  • How do i enable `cachedFileArray`

    How do i enable `cachedFileArray`

    Am unable to remove file from input after adding it, in same way i cant add file when there is file in input.

    https://stackoverflow.com/questions/59195429/unable-to-add-or-remove-image-from-multiple-html-input-field?noredirect=1#comment104610264_59195429

    So how do i enable upload.cachedFileArray

    var upload = new FileUploadWithPreview('myUniqueUploadId', {
      maxFileCount: 4,
      text: {
        chooseFile: 'Maximum 4 Images Allowed',
        browse: 'Add More Images',
        selectedCount: 'Files Added',
      },
    });
    
    opened by sanoj26692 4
  • Not able to get the image on server.

    Not able to get the image on server.

    My html

    <input type="hidden" name="upload_log" id="upload-log" value="" />
       <div class="upload-log-images">
       <div class="custom-file-container" data-upload-id="upload-log-images">
         <label>Upload File <a href="javascript:void(0)" class="custom-file-container__image-clear" title="Clear Image">&times</a></label>
         <label class="custom-file-container__custom-file" >
             <input type="file" class="custom-file-container__custom-file__custom-file-input" accept=".png, .jpg, .jpeg" multiple>
            <input type="hidden" name="MAX_FILE_SIZE" value="10485760" />
           <span class="custom-file-container__custom-file__custom-file-control"></span>
          </label>
          <div class="custom-file-container__image-preview"></div>
            </div>
      </div>
    

    What i understood is i have all the valid images in cachedFileArray.

    I am trying to sending complete array in hidden input.

    window.addEventListener('fileUploadWithPreview:imageDeleted', function(e) {
        if (e.detail.uploadId === 'upload-log-images') {
            jQuery('#upload-log').val(JSON.stringify(e.detail.cachedFileArray))
        }
    })
    

    At the server level.

     $files =   $upload_log = json_decode(utf8_encode(stripslashes($_POST['upload_log'])), true);
    

    output is

    
    Array
    (
        [0] => Array
            (
                [token] => pvf6dfs1p65k520olz9r
            )
    
        [1] => Array
            (
                [token] => 3tii69591shepm5x6apzys
            )
    
    )
    
    opened by insaurabh 4
  • keep original image size in preview.

    keep original image size in preview.

    Hi, ran across this and trying it out. Thanks!

    Using it for one image to test,

    If I choose a small image height x width the preview displays/fills the entire preview area. This could make it blurry.

    I may find this, but thought I'd give a quick ask,

    Is there a way to keep the original image size in the preview area? Get the original image dimensions?

    Thanks much! Appreciate it.

    Didn't see this in the notes.

    Best,

    opened by WriterStat 4
  • Delete Button

    Delete Button

    We got two button 1 delete and another one clear . 1 Delete button only work or seen by multiple image not one . 1 Clear button i mistaken as deleted button which not listen to imageDeleted .

    opened by NobodyButMe-Haiya 4
  •  file_upload_with_preview__WEBPACK_IMPORTED_MODULE_4__.FileUploadWithPreview is not a constructor

    file_upload_with_preview__WEBPACK_IMPORTED_MODULE_4__.FileUploadWithPreview is not a constructor

    Hello @johndatserakis , I am getting this error Uncaught TypeError: file_upload_with_preview__WEBPACK_IMPORTED_MODULE_4__.FileUploadWithPreview is not a constructor in ReactJs v18.2.0

    "file-upload-with-preview": "^5.0.8",

    Here is my sample code

    import "file-upload-with-preview/dist/file-upload-with-preview.min.css";
    import { FileUploadWithPreview } from "file-upload-with-preview";
    
    import React, { useState } from "react";
    
    function Gallery() {
    
      if (typeof window !== "undefined") {
        const upload = new FileUploadWithPreview("file-upload", {
          multiple: true,
        });
      }
    
      return (
        <div
        class="custom-file-container"
        data-upload-id="file-upload"
      ></div>
        );
    
    }
    
    opened by dennohpeter 3
  • Name attribute not present in sending request to server.

    Name attribute not present in sending request to server.

    Hi, I am having an issue that input element attribute name is not present in the dynamically generated field which is causing problems in the server side, then I tried attaching dynamically to it using the Custom JS it gets attached to the input element but still I can not receive the image on the server side, so could you elaborate how to work around with this, thanks for your help, your plugin has been a big help.

    opened by mirfanalikhanprofessional 5
  • Beginner overloaded

    Beginner overloaded

    Please can you create an easy and simple example to run the upload and then use the uploaded file for beginner with nothing more than a webserver, jquery und nothing more (at this step). I dont have npm (and wont use it), because its over-overloaded for a simple upload at my own server for me only. Thanks Bfo

    opened by bforpc 2
Releases(v5.0.8)
  • v5.0.8(Oct 14, 2022)

    What's Changed

    • Fix click event on single upload by @tasinttttttt in https://github.com/johndatserakis/file-upload-with-preview/pull/63

    Full Changelog: https://github.com/johndatserakis/file-upload-with-preview/compare/v5.0.7...v5.0.8

    Source code(tar.gz)
    Source code(zip)
  • v5.0.7(Jul 14, 2022)

  • v5.0.6(Apr 24, 2022)

    • Revamped library
    • Added TypeScript
    • Replaced webpack with vite for example
    • Updated all deps
    • Added prettier and updated eslint
    • Simplified library logic
    • Updated SCSS styling
    Source code(tar.gz)
    Source code(zip)
Owner
John Datserakis
Software Engineer at @indigo-ag.
John Datserakis
Snowfall effect written in pure JavaScript. No additional libraries, no dependencies. Works in every modern browser.

pureSnow.js Snow falling slowly on a winter night. Probably the most calming and peaceful snowfall effect written in pure JS/CSS. (No SCSS). Inspired

null 20 Dec 29, 2022
An enhanced HTML 5 file input for Bootstrap 5.x/4.x./3.x with file preview, multiple selection, and more features.

bootstrap-fileinput An enhanced HTML 5 file input for Bootstrap 5.x, 4.x, and 3.x with file preview for various files, offers multiple selection, resu

Kartik Visweswaran 5.2k Jan 3, 2023
Codebraid Preview provides a Markdown preview for Pandoc documents within VS Code.

Codebraid Preview provides a Markdown preview for Pandoc documents within VS Code. Most Markdown previews don't support all of Pandoc's extensions to Markdown syntax. Codebraid Preview supports 100% of Pandoc features—because the preview is generated by Pandoc itself! There is also full bidirectional scroll sync and document export.

Geoffrey Poore 12 Dec 28, 2022
Get an isolated preview database for every Netlify Preview Deployment

Netlify Preview Database Plugin Create an isolated preview database for each preview deployment in Netlify Quickstart • Website • Docs • Discord • Twi

Snaplet 10 Nov 16, 2022
CLI utility that parses argv, loads your specified file, and passes the parsed argv into your file's exported function. Supports ESM/TypeScript/etc out of the box.

cleffa CLI tool that: Parses argv into an object (of command-line flags) and an array of positional arguments Loads a function from the specified file

Lily Scott 9 Mar 6, 2022
Upload or Upload & Publish your bundle (apk or aab) to Huawei AppGallery with ConnectApi

appgallery-publisher Upload/Publish your bundle (apk or aab) to AppGallery automatically with appgallery-publisher Usage Single Javascript File Bash F

Mustafa YiÄŸit 17 Sep 19, 2022
This project uses clarfai API to get the characteristic of the images uploaded by the user.

Clarfai Project Introduction In this project we will be using Clarifai's API to show characteristic of the images. The clarifai API is a powerful mach

Sai Charan 3 Mar 20, 2022
Twitter bot to find what song is playing in a given uploaded twitter video.

what-song-is-this Twitter bot to find what song is playing in a given uploaded twitter video. How to setup. yarn install How to run. via npm script ya

Akinwande Akinboluwarin 17 Dec 11, 2022
A simple javascript utility library to include partial html (iframe alternate) without a framework or jQuery.

alt-iframe A simple javascript utility library to include partial html (iframe alternate) without a framework or jQuery. <!doctype html> <html lang="e

FrontEndNeo 17 Dec 30, 2022
This is a simple Image popup Jquery plugin. With a very simple configuration, you can show a popup on your webpage. By the way, this plugin works after page load.

Jquery-SingleImagePopup This is a simple Image popup Jquery plugin. With a very simple configuration, you can show a popup on your webpage. By the way

Rajan Karmaker 1 Aug 22, 2022
In this project we made a Tv shows webpage where you can like or comment the different shows.

JS Capstone Project In this project we made a Tv shows webpage where you can like or comment the differents shows. Built With HTML CSS JavaScript Lint

Lucas Bonnefon 4 Mar 16, 2022
TV Shows Web App - A web application based on an external API which contains information about TV shows

TV Shows Web App - A web application based on an external API which contains information about TV shows. th web app let you like the shows that you like the most and comment what you think about them making use of an involvement API to save this interaction information.

Williams Colmenares 14 Dec 17, 2022
TV Shows Web App - A web application based on an external API which contains information about TV shows

TV Shows Web App - A web application based on an external API which contains information about TV shows. th web app let you like the shows that you like the most and comment what you think about them making use of an involvement API to save this interaction information.

Williams Colmenares 14 Dec 17, 2022
Utility for generating preview images of StarCraft: Brood War and Remastered maps

bwpreview Utility for generating preview images of StarCraft: Brood War and Remastered maps (.scm and .scx files). All of the actual work of parsing m

Michiel Sikma 5 Oct 14, 2022
Hacktoberfest is all about meeting up all brains. In this repository we are planning to come with many ideas and works. You all can share your ides/works here.

Hacktoberfest Submit your Work Hacktoberfest is all about meeting up all brains. In this repository we are planning to come with many ideas and works.

Chinmay Patil 3 Oct 5, 2022
Well-tested utility functions dealing with async iterables

aitertools This library provides a well-tested collection of small utility functions dealing with async iterables. You can think of it as LINQ or aite

Hong Minhee (洪 民憙) 11 Aug 15, 2022
Sequential workflow designer written in TypeScript with no dependencies.

Sequential Workflow Designer Sequential workflow designer with no dependencies for web. It's written in pure TypeScript and uses SVG for rendering. Th

Bart Tadych 304 Jan 6, 2023
With this File Manager prepared for PHP/Js, you can perform all file operations on your server without any problems.

FileManager With this File Manager prepared for PHP/Js, you can perform all file operations on your server without any problems. Instead of downloadin

Tanzer Demir 4 Sep 23, 2022
Finally, a simple, lightweight (0.6kb), pure JavaScript image lazy loader that even works in IE* using the IntersectionObserver API

Simply Lazy A simple & lightweight (0.6kb), pure JavaScript image lazy loader that even works in IE* utilizing the built in IntersectionObserver API i

Max 5 Dec 26, 2022