npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

paper-uploader

v0.0.8

Published

A file upload wrapper for paper-uploads based on dropzone.js

Downloads

26

Readme

paper-uploader

Build Status

A file upload wrapper for paper-uploads based on dropzone.js

import { Uploader } from "paper-uploader";


const uploader = new Uploader({
    // DOM-элемент, в область которого можно перемещать файлы 
    // для их загрузки.
    // Required. Default: null
    dropzone: null,

    // URL, на который будут отправляться загружаемые файлы. 
    // Required.
    url: "",

    // Максимальный размер chunk при разбиении больших файлов. 
    // Default: 2 * 1024 * 1024
    chunkSize: 2 * 1024 * 1024,

    // Разрешает загружать несколько файлов разом, аналогично
    // атрибуту multiple тэга <input type="file">.
    // Default: false
    uploadMultiple: true,

    // Имя параметра, через который передаётся файл.
    // Default: "file"
    paramName: "file",

    // Максимально допустимый размер файла в байтах
    maxFilesize: null,

    // Объект (или функция, возвращающая объект), содержащий
    // данные, которые будут отправлены с каждым запросом.
    // Default: null
    params: {
        "author": "Jim"
    },

    // Объект (или функция, возвращающая объект), содержащий
    // HTTP-заголовки, которые будут отправлены с каждым запросом.
    // Default: null
    headers: {
        "X-Author-Name": "Jim"
    },

    // Строки или функции, предназначенные для фильтрации добавляемых файлов.
    // Default: []
    filters: [
        "image/*",
        
        file => {
            // ...
            return false  // skip file
        }
    ],

    // Добавленные файлы сразу будут помещены в очередь на отправку.
    // При значении false, ответственность за начало загрузки лежит
    // на разработчике.
    // Default: true
    autoStart: true,

    // DOM-элемент виджета, в который будет помещён скрытый <input>.
    // Default: document.body
    container: document.body,

    // DOM-элемент (или CSS-селектор), при клике на который вызывается 
    // окно выбора файла.
    // Default: false
    button: false
});

Events

uploader.on("submitted", file => {
    console.log(`File submitted: ${file.name}`);
})

Link: EventEmitter

submit

Format: function(file) {}

Вызывается при добавлении файла в очередь, до любых проверок на валидность файла.

Чтобы отменить добавление файла в очередь, необходимо вызвать в обработчике события исключение с текстом ошибки. Ошибка, созданная таким образом может быть переопределена встроенными проверками (например проверкой максимального размера файла).

submitted

Format: function(file) {}

Вызывается когда файл успешно добавлен в очередь. Подразумевается, что на этой стадии файл уже проверен, поэтому отменять загрузку на этой стадии не стоит.

upload

Format: function(file, xhr, formData) {}

Вызывается прямо перед отправкой файла на сервер. Через аргументы xhr и formData можно модифицировать отправляемые данные.

progress

Format: function(file, progress, bytesSent) {}

Вызывается при обновлении прогресса отправки файла. Аргумент progress - это состояние отправки в процентах (0-100).

cancel

Format: function(file) {}

Вызывается при отмене загрузки файла. Чтобы вызвался этот метод, файл должен пройти стадию submitted.

complete

Format: function(file, response) {}

Событие успешной загрузки файла. Загрузка считается успешной, когда сервер ответил статусом 200.

all_complete

Format: function() {}

Вызывается когда очередь файлов обработана.

error

Format: function(file, message) {}

Обработчик ошибок загрузки. Вызывается не только при JS-ошибках во время отправки файла, но и при получении ошибок валидации от сервера.