🚀 A small JS no-dependency library for a cool download experience

Overview

APE Design


JS File Downloader

Version License

🌟 Please remember to star this github repo if you like it. Thank you! ❤️

Introduction

JS File Downloader is a simple no dependency library you will be able to download file from browser and show downloading status.

Browser Compatibility

JS File Downloader supports all browsers that are [ES5-compliant] (http://kangax.github.io/compat-table/es5/) (IE8 and below are not supported).


Installing with package manager

With a package manager (recommended):

npm install js-file-downloader --save 

Basic usage

import JsFileDownloader from 'js-file-downloader';

const fileUrl = 'http://...';

new JsFileDownloader({ 
    url: fileUrl
  })
  .then(function () {
    // Called when download ended
  })
  .catch(function (error) {
    // Called when an error occurred
  });
  

Use without a package manager

Download this library from https://github.com/AleeeKoi/js-file-downloader/releases

<script src="/path/to/js-file-downloader.min.js"></script>
<script>
  // Then somewhere in your code
  new jsFileDownloader({ url: 'https://cdn.apedesign.net/github/logo.png' })
    .then(function () {
      // Called when download ended
    })
    .catch(function (error) {
      // Called when an error occurred
    });
</script>

Options:

process (for checking download status)

A function to call every time a process event is called. Function receive an Event Object as input.

function process (event) {
  if (!event.lengthComputable) return; // guard
  var downloadingPercentage = Math.floor(event.loaded / event.total * 100);
  // what to do ...
};

new JsFileDownloader({ 
  url: '...',
  process: process
})
  

onloadstart ('loadstart' event listener)

A function to call when a 'loadstart' event is triggered.

function onloadstart () {
  // what to do ...
}

new JsFileDownloader({ 
  url: '...',
  onloadstart
})
  

headers (of request)

If you need to customize request header data you can pass an array of objects like following example:

new JsFileDownloader({ 
  url: '...',
  headers: [
    { name: 'Authorization', value: 'Bearer ABC123...' }
  ]
})

filename

Setting this String you can force output file name

timeout (ms)

Integer value (default 40000) defining how much ms attend before stop download action.

autoStart

Boolean value (default true) to enable/disable automatically starting the download. When the value is true the constructor returns a Promise, however when it's set to false, the constructor doesn't return anything and the download can be started by calling the start() method on the object.

Example with autoStart set to true

new JsFileDownloader({ 
  url: '...',
  autoStart: true
})

Example with autoStart set to false

const download = new JsFileDownloader({ 
  url: '...',
  autoStart: false
});

download.start()
  .then(function(){
      // success 
  })
  .catch(function(error){
      // handle errors
  });

forceDesktopMode

Boolean value (default false) to force desktop mode even on mobile devices for downloading files.

new JsFileDownloader({ 
  url: '...',
  forceDesktopMode: true
})

withCredentials

This is a Boolean that indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies, authorization headers or TLS client certificates. Setting withCredentials has no effect on same-site requests.

new JsFileDownloader({ 
  url: '...',
  withCredentials: true
})

method

The HTTP request method to use, such as "GET", "POST", "PUT", etc. (default "GET") Ignored for non-HTTP(S) URLs.

new JsFileDownloader({ 
  url: '...',
  method: 'POST'
})

nameCallback

You could pass a callback to customize final name, the function receive as 1st argument the name automatically extracted.

new JsFileDownloader({ 
  url: '...',
  nameCallback: function(name) {
    return 'i-am-prefix-' + name;
  }
})

contentType

Setting this property you can customize the content type in the heade request, default is 'application/x-www-form-urlencoded' If you set this property as false, the library doesn't set it.

new JsFileDownloader({ 
  url: '...',
  contentType: 'multipart/form-data; boundary=something' // or false to unset it
})

nativeFallbackOnError

By setting this property to true (default is false) when error occours the download will fallback to the default behavior opening a new tab.

new JsFileDownloader({ 
  url: '...',
  nativeFallbackOnError: true
})

body

By setting this property you can customize the body content sent with the request. Default value is null (nothing is sent), Document or BodyInit value can be set.

new JsFileDownloader({ 
  url: '...',
  body: 'The body as a string'
})

contentTypeDetermination

By setting this property the downloader will determine the content type automatically depending on the value.

value description
"header" Gets type from content-type response header.
"signature" Analyzes the first 4 bytes of the returned file and will check if that signature exists in the predetermined dict (You can override/merge this dict with the customFileSigantures property).
"full" Uses both methods from above but prefers "siganture".
false Type is not determined and the default is added, application/octet-stream.
new JsFileDownloader({ 
  url: '...',
  contentTypeDetermination: 'header'
})

customFileSignatures

By setting this value you can override/merge the predefined signature dict (src/signatures.js). The key represents the hex code of a file (for more information here) and the value should be in the format of a content type (e.g. application/pdf). Setting this value has only an affect when contentTypeDetermination is set to "full" or "signature".

new JsFileDownloader({ 
  url: '...',
  contentTypeDetermination: 'full', // must be set to "full" or "signature"
  customFileSignatures: {
    'FFFB':'audio/mpeg',
    'FFF3':'audio/mpeg',
    'FFF2':'audio/mpeg',
    '494433': 'audio/mpeg'
  }
})

License

MIT

Copyright (c) 2019-present, Alessandro Pellizzari

apedesign.net

Comments
  • Webpack imported module 0 is not defined

    Webpack imported module 0 is not defined

    Hi, I'm creating a chrome extension and I got this error when I tried to import the library

    Uncaught ReferenceError: js_file_downloader__WEBPACK_IMPORTED_MODULE_0__ is not defined
    

    I'm tried to import using jsFileDownloader, JsFileDownloader and with curly braces but it didn't worked. How can I fix this?

    Waiting user feedback 
    opened by hugorplobo 7
  • Always reject the download promise with a `downloadException`

    Always reject the download promise with a `downloadException`

    It is useful to always reject a promise with an Error (superclass of downloadException). Using an Error ensures you have access to stack traces which can help with debugging: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/reject#description

    In our case, using an Error as the reject reason would help give Sentry better error information: https://github.com/getsentry/sentry-javascript/issues/2546#issuecomment-645357265

    opened by micthiesen 6
  • Any support for passing cookies with request

    Any support for passing cookies with request

    Hi, I want to ask is there any support for sending cookies with the request just like we can do with the JS Fetch by adding credentials: 'include' or with the XMLHttpRequest just by adding request.withCredentials = true;.

    Kindly can anyone help me with this?

    opened by skashanali 5
  • createObjectURL

    createObjectURL

    When trying to use it in a Cordova-electron app I get this error: Uncaught (in promise) TypeError: Failed to execute 'createObjectURL' on 'URL': Overload resolution failed. at t. (js-file-downloader.min.js:10)

    (does not depend on the file type or server).

    opened by shahind 4
  • Error status code

    Error status code

    I don't see any way to get the status code from the error message thrown. Use case = 401 (Unauthorized) refresh users token and try again.

    Looking a bit more into it the exceptions just might not be working correctly, the lib attempts to use -

    https://github.com/AleeeKoi/js-file-downloader/blob/master/src/exception.js

    Which then throws -

    Error: Downloader error: TypeError: Cannot set property 'message' of undefined at XMLHttpRequest.request.onload (js-file-downloader.js:217)

    Which prevents the error message from properly getting emitted out.

    opened by JacobSiegle 4
  • Multiple download and checking download status of each file

    Multiple download and checking download status of each file

    I need to download multiple files and show the status of eatch downloaded file... So i create for loop. Is there any way to add to information into process function about file status HTML element?

    thanks

    opened by AdamReznicek 3
  • TypeScript: Array of headers

    TypeScript: Array of headers

    Hi. There is a small typo in the current type definition of headers. Written this way it allow only 1 header : headers?: [{ name: string, value: string }];

    To allow multiple headers, the correct syntax is headers?: { name: string, value: string }[]

    (or it could be Array<{ name: string, value: string }>)

    opened by mbaroukh 3
  • Append filename with mime type

    Append filename with mime type

    Hey, I was wondering if you ever thought about appending the filename with the correct ending (e.g .pdf) following the mime type returned from the server. I implemented something like that with js-file-download but this package doesn't have type declarations.

    Here a snippet:

    axios
      .get(url, {
        responseType: 'blob',
      })
      .then((response) => response.data)
      .then((blob) => {
        // fileDownload is the function of the js-file-download library
        // It accepts the following: 
        // data: string | ArrayBuffer | ArrayBufferView | Blob,
        // filename: string,
        // mime?: string,
        // bom?: string
        fileDownload(blob, generateFilename(filename), blob.type);
      })
      .catch((error) => {
        console.error(error);
        throw error;
      });
    

    The library does support a custom mime and what I did is just using the one which the blob reflects. Would be cool to have some ability to turn this on automatically.

    What are your thoughts? Let me know 😉

    enhancement 
    opened by marvin-kolja 3
  • Cannot set body on POST request.

    Cannot set body on POST request.

    Hello! Trying to get file, but i need to make a POST request with params. A pdf file will be generated with params, that must be send in post request, like name and so on.

    new JsFileDownloader({
            url: process.env.REACT_APP_API_URL + url,
            headers: [{ name: "authorization", value: `Bearer ${token}` }],
            method: "POST",
            withCredentials: true,
            filename: "NDA.pdf",
            contentType: "application/json;charset=UTF-8",
          }) //@ts-ignore
            .catch(function (error) {
              console.dir("download error", error);
             
            });
    

    Can you add a body field for POST request ?

    enhancement 
    opened by copperfox777 3
  • Content-Type should not bet set for GET-Requests

    Content-Type should not bet set for GET-Requests

    request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

    sets a content-type for every request, even for GET requests where there is no Body, and thus no content-type. https://stackoverflow.com/questions/5661596/do-i-need-a-content-type-header-for-http-get-requests

    This causes issues for some REST-Frameworks and Firewalls, complaining about content-type being set without body.

    enhancement 
    opened by k-a-z-u 3
  • mobileDisabled is not used

    mobileDisabled is not used

    There is a parameter mobileDisabled but it's not used anywhere in the code. Or did I miss something?

    The code and doc would probably require clarification in regards to that parameter and forceDesktopMode, to clearly explain how to make it work on mobile.

    For instance the doc mentions that mobileDisableddefaults to false, while it's true in the code. But anyhow this parameter is not used.

    opened by gotson 3
  • Issue downloading a large file

    Issue downloading a large file

    Hello and thanks for this great library.

    I'm having issues with a specific file, with is a large video (3.1GB), and stored on Amazon S3. It seems that the file is being downloaded, I can see the progress through the process callback. Once the downloading is complete, the file is saved, but instead of the expected video file, there is a 4 bytes file, which is just a text file containing the string "null".

    Any ideas?

    Thanks, Tom

    enhancement todo 
    opened by TomRaz 7
  • Download files using HTTPS throw error on console

    Download files using HTTPS throw error on console

    I am using the latest version of this package minified for an internal project of the company I work and I noticed that when using HTTPS and trying to download files in different formats it throws an error on the console. vmconnect_C0xhse8b6L But this only happens on the first try, on the next's one the download proceeds correctly and no errors are shown. Our source code that this happen is something like this vmconnect_OYNd3EWvOd I enabled the nativeFallbackOnError to true and the error was vmconnect_NpbZhz3keL So I tried debugging this function and also the endpoint and it seems that after returning the file to download it cannot be read and the error.request.response is null and the responseText is filled with [Exception: DOMException: Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was 'arraybuffer'). vmconnect_ntIhnHOFTo

    Waiting user feedback 
    opened by cfthody 4
  • Not downloading on chrome mobile

    Not downloading on chrome mobile

    For whatever reason, this does not appear to work on chrome mobile on iOS. It seems to download, but nothing ends up in our files. I believe this used to work so possibly something changed on chrome. It works on safari. This is how we call the JsFileDownloader:

    new JsFileDownloader({
        forceDesktopMode: true,
        withCredentials: true,
        nativeFallbackOnError: true,
        headers: [
          {
            name: "timezoneOffset",
            value: new Date().getTimezoneOffset().toString(),
          },
        ],
        url: process.env.REACT_APP_API_URL + `${endpoint}?${stringify(params)}`,
    
    enhancement Waiting user feedback todo 
    opened by jacten 2
Releases(v.1.1.24)
  • v.1.1.24(Dec 6, 2021)

    Notes:

    • added contentTypeDetermination, by setting this property the downloader will determine the content type automatically depending on the value;
    • doc and example fix;
    • ts definition fix.

    ⭐ If you like it please star this repo 🤟

    Also thanks to: @marvin-kolja @techieshark @mbaroukh

    Source code(tar.gz)
    Source code(zip)
  • 1.1.23(Nov 23, 2021)

  • v1.1.21(Aug 18, 2021)

    Notes:

    • added option body, by setting this property you can customize the body content sent with the request. Default value is null (nothing is sent), Document or BodyInit value can be set.
    • added nativeFallbackOnError, by setting this property to true (default is false) when error occours the download will fallback to the default behavior opening a new tab.

    ⭐ If you like it please star this repo 🤟

    Source code(tar.gz)
    Source code(zip)
  • v.1.1.20(Jun 5, 2021)

  • v1.1.19(Apr 9, 2021)

    Notes:

    • always reject the download promise with a DownloadException (thanks to @micthiesen)
    • deprecated old exception name downloadException (it will be removed in next releases)
    • updated dependencies

    ✨ If you like it please star this repo ❤️

    Source code(tar.gz)
    Source code(zip)
  • v1.1.18(Mar 24, 2021)

  • v1.1.17(Mar 24, 2021)

  • v1.1.16(Mar 9, 2021)

  • v1.1.15(Oct 22, 2020)

  • v1.1.14(Oct 22, 2020)

  • v1.1.13(Oct 15, 2020)

  • v1.1.12(Oct 15, 2020)

    Release notes:

    • added index.d.ts file
    • fix the Exception named downloadException
    • added param 'request' to the downloadExceptionobject

    ✨ If you like it please star this repo ❤️

    Source code(tar.gz)
    Source code(zip)
  • v1.1.11(Sep 1, 2020)

  • v1.1.9(Jul 9, 2020)

  • v1.1.8(May 25, 2020)

  • v1.1.7(Apr 23, 2020)

    Notes:

    • Added support for XMLHttpRequest.withCredentials

    The XMLHttpRequest.withCredentials property is a Boolean that indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies, authorization headers or TLS client certificates. Setting withCredentials has no effect on same-site requests. Source: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials

    Thanks to: @skashanali

    Source code(tar.gz)
    Source code(zip)
  • v1.1.6(Apr 6, 2020)

  • 1.1.5(Dec 18, 2019)

    New features:

    • Added an option to force desktop mode
    • Added an option to disable automatically starting of downloads (backwards compatible)
    Source code(tar.gz)
    Source code(zip)
  • 1.1.4(Sep 12, 2019)

  • 1.1.3(Sep 1, 2019)

  • 1.1.2(Jul 25, 2019)

Owner
AleeeKoi
I'm a freelance full-stack developer, I like to code using VueJS & Laravel.
AleeeKoi
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
A small javascript DOM manipulation library based on Jquery's syntax. Acts as a small utility library with the most common functions.

Quantdom JS Quantdom is a very small (about 600 bytes when ran through terser & gzipped) dom danipulation library that uuses a Jquery like syntax and

Sean McQuaid 7 Aug 16, 2022
Small, typed, dependency free tool to round corners of 2d-polygon provided by an array of { x, y } points.

round-polygon Small, typed, dependency-free tool to round corners of 2d-polygon provided by an array of { x, y } points. The algorithm prevents roundi

Sergey Borovikov 10 Nov 26, 2022
✏️ A small jQuery extension to turn a static HTML table into an editable one. For quickly populating a small table with JSON data, letting the user modify it with validation, and then getting JSON data back out.

jquery-editable-table A small jQuery extension to turn an HTML table editable for fast data entry and validation Demo ?? https://jsfiddle.net/torrobin

Tor 7 Jul 31, 2022
JavaScript/TypeScript library to run repetitive tasks with throttle control and other cool features

Repeatify JavaScript/TypeScript library to run repetitive tasks with throttle control and other cool features Install npm install repeatify Usage impo

Evert Arias 2 Jan 15, 2022
Tool Cool Color Picker is a color picker library written in typescript and using web component technologies.

Tool Cool Color Picker Tool Cool Color Picker is a color picker library written in typescript and using web component technologies. Check out the demo

Tool Cool 13 Oct 23, 2022
We are creating a Library that would ensure developers do not reinvent the wheel anymore as far as Authentication is concerned. Developers can easily register and download authentication codes that suits their need at any point.

#AuthWiki Resource Product Documentation Figma Database Schema First Presentation Live Link API Documentation Individual Contributions User Activity U

Zuri Training 17 Dec 2, 2022
A Javascript library to export svg charts from the DOM and download them as an SVG file, PDF, or raster image (JPEG, PNG) format. Can be done all in client-side.

svg-exportJS An easy-to-use client-side Javascript library to export SVG graphics from web pages and download them as an SVG file, PDF, or raster imag

null 23 Oct 5, 2022
A Javascript library that discourages and prevents image theft/download by preventing client ability to retrieve the image.

ProtectImage.js ProtectImage.js is a Javascript library that helps prevent image theft by disabling traditional user interactions to download/copy ima

null 4 Aug 18, 2022
Library to download binary files from GitHub releases detecting the correct platform.

Dbin TypeScript library to download binary files from GitHub releases detecting the correct platform. Example: import dbin from "https://deno.land/x/d

Óscar Otero 7 Oct 4, 2022
Omnichannel Live Chat Widget UI Components offers a re-usable component-based library to help create a custom chat widget that can be connected to the Dynamics 365 Customer Service experience.

Omnichannel Live Chat Widget UI Components @microsoft/omnichannel-chat-widget is a React-based UI component library which allows you to build your own

Microsoft 14 Dec 15, 2022
Simple, fast, accessible accordion library with no dependency

React Fast Accordion ⚡️ Dynamic, fast, accessible & zero dependency accordion for React How it's fast? Instead of adding event listener on all the ite

Shivam 59 Oct 8, 2022
A TypeScript library for creating dependency snapshots.

Dependency Submission Toolkit @github/dependency-submission-toolkit is a TypeScript library for creating dependency snapshots and submitting them to t

GitHub 19 Nov 22, 2022
EggyJS is a Javascript micro Library for simple, lightweight toast popups focused on being dependency-less, lightweight, quick and efficient.

EggyJS EggyJS is a Javascript micro Library for simple, lightweight toast popups. The goal of this library was to create something that meets the foll

Sam 10 Jan 8, 2023
A functional, immutable, type safe and simple dependency injection library inspired by angular.

func-di English | 简体中文 A functional, immutable, type safe and simple dependency injection library inspired by Angular. Why func-di Installation Usage

null 24 Dec 11, 2022
A dependency-free JavaScript library for creating discreet pop-up notifications.

Polipop A dependency-free JavaScript library for creating discreet pop-up notifications. Demo See demo at minitek.github.io/polipop/. Documentation Se

Minitek 8 Aug 15, 2022
The repository contains the list of awesome✨ & cool web development beginner-friendly✌️ projects!

Web-dev-mini-projects The repository contains the list of awesome ✨ & cool web development beginner-friendly ✌️ projects! Web-dev-mini-projects ADD AN

Ayush Parikh 265 Jan 3, 2023
A pretty cool org-mode -> interactive blog post tool

Radish A kinda-cool org-mode -> interactive blog post tool written with and for Clojure(script). Here are two example posts created with this tool: Ra

adam-james 46 Dec 28, 2021