Carga de archivos uppy -

Una de las grandes tareas que me encargaron en mi primer trabajo fue configurar un sistema mediante el cual cualquier cliente o cliente potencial (también conocido como usuario anónimo) pudiera cargar archivos PDF y de imágenes. Tenía muchas limitaciones con las que lidiar: soporte del navegador, configuración del servidor, variación en el conocimiento tecnológico del usuario, etc. Al final, necesitábamos usar un subprograma de Java (!) para realizar el trabajo. Bruto.

Afortunadamente, todas las limitaciones con las que tuve que lidiar en aquel entonces mejoraron y la mayoría de las limitaciones que enfrenté se resolvieron. Hoy podría usar Uppy, una utilidad robusta, elegante y de código abierto para cargar archivos. Es súper personalizable y fácil de implementar para usted, el desarrollador y para sus usuarios. ¡Echemos un vistazo!

Índice de contenidos
  1. Consejos Rapidos
  2. Demostración de un vistazo
  3. Implementación del cargador de archivos Uppy
  4. Uppy Server
  5. Transloadit

Consejos Rapidos

  • ¡Fuente abierta!
  • Se requiere muy poco código para implementar
  • El widget de interfaz es elegante y fácil de usar.
  • Las cargas pueden realizarse sin recargar la página
  • Recuperación de estado (hacer que las cargas sobrevivan fallas del navegador o navegaciones accidentales)
  • Funciona bien en el móvil
  • Funciona con cualquier marco de JavaScript
  • Proporciona una amplia gama de complementos para enriquecer la experiencia de carga.
  • Cadenas fáciles de localizar (proporcione su propio idioma pirata, ¡Shiver me Timbers!)
  • Puede cargar en su servidor Apache existente (XHR)
  • o: Puede cargar directamente a S3
  • o: Puede realizar cargas en un servidor habilitado para Tus (lo que hace que las cargas sobrevivan a los viajes ya las malas condiciones de la red)
  • Proporciona una utilidad de servidor que permite a sus usuarios realizar búsquedas desde Google Drive, Dropbox e Instagram.
  • Presentado por la gente detrás deTransloadit. Ofrecen funciones de codificación y versiones alojadas de la utilidad Uppy Server y Tus.

Demostración de un vistazo

Eche un vistazo al uso del widget de Uppy en acción:

El widget Uppy:

  • proporciona una interfaz elegante y bien diseñada
  • funciones de carga de archivos mediante arrastrar y soltar
  • permite la carga pausable y reanudable
  • proporciona un método para cambiar el nombre de los archivos cargados

¡Echemos un vistazo al código para armar esto!

Implementación del cargador de archivos Uppy

Los creadores de Uppy acertaron en la implementación: hacer que el desarrollador implemente la menor cantidad de código necesario para tener una utilidad funcional “in situ”. Comenzando instalando Uppy:

Agregue las bibliotecas CSS y JavaScript a la página:

!-- En el encabezado --link href="https://transloadit.edgly.net/releases/uppy/v0.25.2/dist/uppy.min.css" rel="stylesheet"!-- Donde el arrastre y la caída será --div/div!-- Parte inferior de la página --script src="https://transloadit.edgly.net/releases/uppy/v0.25.2/dist/uppy.min.js"/script

¡Entonces inicializa Uppy!

script var uppy = Uppy.Core({ autoProceed: false }) uppy.use(Uppy.Dashboard, { target: '#drag-drop-area', inline: true }) uppy.use(Uppy.XHRUpload, { endpoint: 'https://mywebsite.com/receive-file.php' })/script

Boom! You have an awesome file upload utility with little hassle that looks great! Check out thelive version on CodePen

If you don’t want to run Uppy of a CDN and prefer to build it yourself with Browserify or Webpack, just use npm instead:

npm install uppy --save
scriptvar Uppy = require('uppy/lib/core')var Dashboard = require('uppy/lib/plugins/Dashboard')var XHRUpload = require('uppy/lib/plugins/XHRUpload')const uppy = Uppy({ autoProceed: false })uppy.use(Dashboard, { target: '#drag-drop-area', inline: true })uppy.use(XHRUpload, { endpoint: 'https://mywebsite.com/receive-file.php' })/script

Uppy also provides you a number ofevents for file uploads:

uppy.on('file-added', (file) = {  // Do something});uppy.on('upload', (data) = {  // Do something})uppy.on('complete', (result) = {  // Do something})

Uppy’s API is so easy to use that you can consider it a “drop in” API for incredible JavaScript uploading

Want to use any of the Uppy plugins? It’s actually pretty easy — let’s check out implementation of what everyone expects from uploads these days, drag drop:

const Dashboard = require('uppy/lib/plugins/Dashboard')uppy.use(Dashboard, { target: '#drag-drop-area', inline: true })

TheDashboard plugin here renders a clean and simple drag and drop area, shows file previews, lets you edit meta data and shows upload progress. It acts as a host for other plugins. When you add the Webcam or Instagram plugins, they appear in the Dashboard as tabs, and your users can then select files from any of those as well.

Now let’s add theWebcam plugin:

const Webcam = require('uppy/lib/plugins/Webcam')uppy.use(Webcam, {  countdown: false,  mirror: true,  facingMode: 'user',  target: Dashboard // Webcam will be installed to the Dashboard})

Dashboard+Webcam Demo on CodePen

Uppy Server

With theXHRUpload plugin Uppy will upload to your existing Apache/Nginx/Node.js/Ruby/PHP server from local disk or webcam. No Uppy Server required. If however you want to add fetching files from Dropbox and Instagram, you will need to run an Uppy Server in the cloud. Uppy Server is open source as well, so you can host it yourself. The API docs are super detailed!

The advantages of having a helper like Uppy Server in the cloud are clear. If your user is on mobile, and picks a 5GB file from their Dropbox, it won’t have to be fetched to their phone, and then uploaded. Instead, the file is moved directly between servers. This saves a lot of bandwidth and battery. This is what Uppy Server facilitates, as well as managing the secrets required to access these files.

Let’s look at a demo how you could easily allow fetching fromremote providers like Google Drive and Dropbox or a plain accessible URL:

const GoogleDrive = require('uppy/lib/plugins/GoogleDrive')const Url = require('uppy/lib/plugins/Url')// remote providers require the uppy server utility. // we're using the public demo server in this case:uppy.use(GoogleDrive, { target: Dashboard, host: 'https://server.uppy.io/' })uppy.use(Url, { target: Dashboard, host: 'https://server.uppy.io/ })

If you decide you want Uppy Server but not host it, you could also letTransloadit handle that. Transloadit created both Uppy and the Tus standard. It might come in handy that Transloadit also offers integrated virus scan, image crop, transcode, face detect, and more. They will store the results on storage of your choosing. This way you’ll always own all content, and you can be confident that what is uploaded, displays optimally on all devices and browsers.

Transloadit

I hadn’t heard about Transloadit before but it seems they’re a small remote company that’s been relentlessly trying to advance the file uploading processing space, and that the majority of their tech has been released as open source

Transloadit‘s uploading and processing service delivers an awesome array of functionality:

  • Resize, crop, and watermark images
  • Convert videos to GIFs, and visa versa
  • Transcode video and extract thumbnails
  • Take website screenshots
  • Create waveform images from audio
  • Create slideshow videos from images and audio
  • Chain conversions together to create unique “workflows” in a single declaritive JSON language
  • Stability of 99.99% uptime over 9 years
  • Manipulate media on the fly
  • Integrates well for different media types and different languages and frameworks
  • Trusted by Coursera, The New York Times, Oracle, Cambridge University, and more

As a final demo, let’s look at a simple example of how Uppy plays with Transloadit, for when you want to, say, add a “Powered by Uppy” text to images that your users are uploading:

const Uppy = require('uppy/lib/core')const Dashboard = require('uppy/lib/plugins/Dashboard')const Transloadit = require('uppy/lib/plugins/Transloadit')const uppy = Uppy() . use(Dashboard, { target: '#drag-drop-area', inline: true }) .use(Transloadit, { waitForEncoding: true, params: { auth: { key: YOUR_TRANSLOADIT_KEY }, pasos: { redimensionar: { ancho: 250, altura: 250, robot: '/image/resize', texto: [{'text': 'Powered by Uppy', 'font': 'Ubuntu', 'color': '#eeeeee', 'valign': 'bottom', 'align': 'right', 'x_offset': 16, 'y_offset': -10}] } } } })uppy.on('transloadit:result', (stepName, result) = { // use el resultado de codificación transloadit aquí. console.log('Resultado aquí ====', nombre del paso, resultado) console.log('La URL de la imagen recortada está aquí ====', resultado.url)})

Vea una demostración interactiva de Uppy+Transloadit

Administrar la carga de archivos, tanto desde la perspectiva del cliente como del servidor, puede ser una pesadilla total; Agregue lo difícil que puede ser la validación de arrastrar, soltar y cargar y tener un cargador de archivos increíble parece un unicornio. Uppy parece el verdadero negocio: configurable, fácil de implementar, interfaz de usuario elegante, control de servidor, código abierto, moderno, modular y más: ¡no se puede pedir mucho más!

Te podría interesar...

Deja una respuesta

Subir