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

simplejs-upload

v1.0.2

Published

A jQuery plugin for simple upload

Downloads

15

Readme

simpleUpload Jquery Ajax upload

simpleUpload é um simples Jquery plugin para facilitar o envio de arquivos sem depender de um formulário.

Usage

Html

<input type="file" name="arquivo" id="simpleUpload" multiple >
<button type="button" id="enviar">Enviar</button>

Javascript

$('#simpleUpload').simpleUpload({
	url: 'upload.php',
	trigger: '#enviar',
	success: function(data){
		alert('Envio com sucesso');
	}
});

PHP

	$arquivo = $_FILES['arquivo'];

Se o parâmetro trigger não for definido o envio será iniciado no evento change do elemento.

Data atribute

Todos os parâmetros podem ser enviados via atributo

<input type="file" name="arquivo_1" class="upload" data-trigger="#enviar1" data-url="upload1.php" multiple >
<button type="button" id="enviar1">Enviar 1</button>

<input type="file" name="arquivo_2" class="upload" data-trigger="#enviar1" data-url="upload2.php" multiple >
<button type="button" id="enviar2">Enviar 2</button>
$('.upload').simpleUpload();

On file change

Callback no evento change do elemento com retorno dos metadados do arquivo

$('#simpleUpload').simpleUpload({
	url: 'upload.php',
	change: function(files){
		$.each(files, function(i, file){
			alert('Nome: '+file.name+' - Tamanho: '+file.size+' - Tipo: '+file.type);
		});
	}
});

Valores extras

O parâmetro fields recebe um json com campos a serem enviados ao Backend

$('#simpleUpload').simpleUpload({
	fields: {
		valor : 'Valor 1',
		array : ['array 1', 'array 2']
	}
});
	$arquivo = $_FILES['arquivo'];
	$valor = $_POST['valor'];
	$array = $_POST['array'];

	echo $valor;
	echo $array[0];
	echo $array[1];

Adicionando valores antes de enviar

Podemos adicionar mais valores no momento antes de envio ( Esse recurso pode ser utilizado para qualquer Ajax )

$('#simpleUpload').simpleUpload({
	fields: {
		valor : 'Valor 1',
		array : ['array 1', 'array 2']
	},
	beforeSend: function(xhr, settings){
		settings.data.append('valorAdicional1', 1);
		settings.data.append('valorAdicional2', 'Valor adicional a ser enviado');
	},
});

Arquivos permitidos

O parâmetro types recebe a lista de extensões permitidas, em caso de arquivo inválido retorna o método error com o parametro erro e o atributo type com o valor 'fileType'

$('#simpleUpload').simpleUpload({
	types: ['jpg', 'png', 'pdf'],
	error: function(erro){
		if(error.type == 'fileType') alert('Arquivo inválido.');
	}
});

Tamanho permitido

O tamanho máximo por arquivo por padrão é 5mb para mudar use o parâmetro size o valor deve ser passado em kb, em caso de tamanho inválido retorna o método error com o parametro erro e o atributo type com o valor 'size'

$('#simpleUpload').simpleUpload({
	size: 3072, // 3 mb
	types: ['jpg', 'png', 'pdf'],
	error: function(erro){
		if(error.type == 'size'){
			alert('Tamanho não permitido.');
		}else if(error.type == 'fileType'){
			alert('Arquivo inválido.');
		}else{
			...
		}
	}
});

O método error chamado para arquivos inválidos fora o tamanho e para erro no retorno do Ajax

Outros parâmetros

O simpleUpload suporta a maioria dos parâmetros que o $.ajax() suporta.

Os parâmetros são:

  • url ( string: Caminho do arquivo Backend )
  • change ( function: método onChange do input file )
  • types ( array: lista de extensões permitidas )
  • size ( int: tamanho permitido em kb )
  • fields ( json: campos extra a serem enviados aceita array )
  • error ( function: retorno de erro )
  • success ( function: retorno de sucesso )
  • beforeSend ( function: executado antes de enviar )
  • async
  • global
  • dataType
  • contents
  • jsonp
  • jsonpCallback
  • password
  • username
  • statusCode

Exemplo back-end PHP

Com o seguinte cenário vamos fazer o upload de multiplos arquivos e resgatar com o PHP

<input type="file" name="arquivo" id="simpleUpload" multiple >
<button type="button" id="enviar">Enviar</button>
<script>
	$(document).ready(function(){
		$('#simpleUpload').simpleUpload({
			url: 'upload.php',
			trigger: '#enviar',
			success: function(data){
				alert('Envio com sucesso');
			}
		});
	});
</script>

Eu costumo criar um função que organiza os arquivos recebidos para ficar mais fácil a manipulação

function orderUpload(&$file){
	$orderedFiles = array();
	$count = count($file['name']);
	$keys = array_keys($file);

	for ($i=0; $i<$count; $i++) foreach ($keys as $key){
		if('name' == $key){
			$file_ary[$i]['extension'] =  strtolower(strrchr($file[$key][$i],"."));
		}
		$orderedFiles[$i][$key] = $file[$key][$i];
	}

	return $orderedFiles;
}

Vamos criar o arquivo upload.php que ira receber os aruquivos e salvar em uma pasta

	$arquivos = orderUpload($_FILES['arquivo']); // Chama a função que retorno os arquivos de forma organizada
	$path     = '/tmp';

	foreach ($arquivos as $k => $arquivo) {

		$fileName = $path . '/arquivo-' . $k . $arquivo['extension'];
		$uploaded = move_uploaded_file($arquivo['tmp_name'], $fileName );

		if($uploaded){
			echo "Arquivo salvo com sucesso!";
		}else{
			echo "Erro ao salvar o arquivo!";
		}
	}

Autor