|
1 |
| -# Resumable file upload |
| 1 | +# Carga de archivos reanudable |
2 | 2 |
|
3 |
| -With `fetch` method it's fairly easy to upload a file. |
| 3 | +Con el método `fetch` es bastante fácil cargar un archivo. |
4 | 4 |
|
5 |
| -How to resume the upload after lost connection? There's no built-in option for that, but we have the pieces to implement it. |
| 5 | +¿Cómo reanudar la carga de un archivo despues de perder la conexión? No hay una opción incorporada para eso, pero tenemos las piezas para implementarlo. |
6 | 6 |
|
7 |
| -Resumable uploads should come with upload progress indication, as we expect big files (if we may need to resume). So, as `fetch` doesn't allow to track upload progress, we'll use [XMLHttpRequest](info:xmlhttprequest). |
| 7 | +Las cargas reanudables deberían venir con indicación de progreso, ya que esperamos archivos grandes (Si necesitamos reanudar). Entonces, ya que `fetch` no permite rastrear el progreso de carga, usaremos [XMLHttpRequest](info:xmlhttprequest). |
8 | 8 |
|
9 |
| -## Not-so-useful progress event |
| 9 | +## Evento de progreso poco útil |
10 | 10 |
|
11 |
| -To resume upload, we need to know how much was uploaded till the connection was lost. |
| 11 | +Para reanudar la carga, necesitamos saber cuánto fue cargado hasta la pérdida de la conexión. |
12 | 12 |
|
13 |
| -There's `xhr.upload.onprogress` to track upload progress. |
| 13 | +Disponemos de `xhr.upload.onprogress` para rastrear el progreso de carga. |
14 | 14 |
|
15 |
| -Unfortunately, it won't help us to resume the upload here, as it triggers when the data is *sent*, but was it received by the server? The browser doesn't know. |
| 15 | +Desafortunadamente, esto no nos ayudará a reanudar la descarga, Ya que se origina cuando los datos son *enviados*, ¿pero fue recibida por el servidor? el navegador no lo sabe. |
16 | 16 |
|
17 |
| -Maybe it was buffered by a local network proxy, or maybe the remote server process just died and couldn't process them, or it was just lost in the middle and didn't reach the receiver. |
| 17 | +Tal vez fue almacenada por un proxy de la red local, o quizá el proceso del servidor remoto solo murió y no pudo procesarla, o solo se perdió en el medio y no alcanzó al receptor. |
18 | 18 |
|
19 |
| -That's why this event is only useful to show a nice progress bar. |
| 19 | +Es por eso que este evento solo es útil para mostrar una barra de progreso bonita. |
20 | 20 |
|
21 |
| -To resume upload, we need to know *exactly* the number of bytes received by the server. And only the server can tell that, so we'll make an additional request. |
| 21 | +Para reanudar una carga, necesitamos saber *exactamente* el número de bytes recibidos por el servidor. Y eso solo lo sabe el servidor, por lo tanto haremos una solicitud adicional. |
22 | 22 |
|
23 |
| -## Algorithm |
| 23 | +## Algoritmos |
24 | 24 |
|
25 |
| -1. First, create a file id, to uniquely identify the file we're going to upload: |
| 25 | +1. Primero, crear un archivo id, para únicamente identificar el archivo que vamos a subir: |
26 | 26 | ```js
|
27 | 27 | let fileId = file.name + '-' + file.size + '-' + +file.lastModifiedDate;
|
28 | 28 | ```
|
29 |
| - That's needed for resume upload, to tell the server what we're resuming. |
| 29 | + Eso es necesario para reanudar la carga, para decirle al servidor lo que estamos reanudando. |
30 | 30 |
|
31 |
| - If the name or the size or the last modification date changes, then there'll be another `fileId`. |
| 31 | + Si el nombre o tamaño de la última fecha de modificación cambia, entonces habrá otro `fileId`. |
32 | 32 |
|
33 |
| -2. Send a request to the server, asking how many bytes it already has, like this: |
| 33 | +2. Envía una solicitud al servidor, preguntando cuántos bytes tiene, así: |
34 | 34 | ```js
|
35 | 35 | let response = await fetch('status', {
|
36 | 36 | headers: {
|
37 | 37 | 'X-File-Id': fileId
|
38 | 38 | }
|
39 | 39 | });
|
40 | 40 |
|
41 |
| - // The server has that many bytes |
| 41 | + // El servidor tiene tanta cantidad de bytes |
42 | 42 | let startByte = +await response.text();
|
43 | 43 | ```
|
44 | 44 |
|
45 |
| - This assumes that the server tracks file uploads by `X-File-Id` header. Should be implemented at server-side. |
| 45 | + Esto asume que el servidor rastrea archivos cargados por el encabezado `X-File-Id`. Debe ser implementado en el lado del servidor. |
46 | 46 |
|
47 |
| - If the file doesn't yet exist at the server, then the server response should be `0` |
| 47 | + Si el archivo no existe aún en el servidor, entonces su respuesta debe ser `0`. |
48 | 48 |
|
49 |
| -3. Then, we can use `Blob` method `slice` to send the file from `startByte`: |
| 49 | +3. Entonces, podemos usar el método `Blob` `slice` para enviar el archivo desde `startByte`: |
50 | 50 | ```js
|
51 | 51 | xhr.open("POST", "upload", true);
|
52 | 52 |
|
53 |
| - // File id, so that the server knows which file we upload |
| 53 | + // Archivo, de modo que el servidor sepa qué archivo subimos |
54 | 54 | xhr.setRequestHeader('X-File-Id', fileId);
|
55 | 55 |
|
56 |
| - // The byte we're resuming from, so the server knows we're resuming |
| 56 | + // El byte desde el que estamos reanudando, así el servidor sabe que estamos reanudando |
57 | 57 | xhr.setRequestHeader('X-Start-Byte', startByte);
|
58 | 58 |
|
59 | 59 | xhr.upload.onprogress = (e) => {
|
60 | 60 | console.log(`Uploaded ${startByte + e.loaded} of ${startByte + e.total}`);
|
61 | 61 | };
|
62 | 62 |
|
63 |
| - // file can be from input.files[0] or another source |
| 63 | + // El archivo puede ser de input.files[0] u otra fuente |
64 | 64 | xhr.send(file.slice(startByte));
|
65 | 65 | ```
|
66 | 66 |
|
67 |
| - Here we send the server both file id as `X-File-Id`, so it knows which file we're uploading, and the starting byte as `X-Start-Byte`, so it knows we're not uploading it initially, but resuming. |
| 67 | + Aquí enviamos al servidor ambos archivos id como `X-File-Id`, para que de esa manera sepa que archivos estamos cargando, y el byte inicial como `X-Start-Byte`, para que sepa que no lo estamos cargando inicialmente, si no reanudándolo. |
68 | 68 |
|
69 |
| - The server should check its records, and if there was an upload of that file, and the current uploaded size is exactly `X-Start-Byte`, then append the data to it. |
| 69 | + El servidor debe verificar sus registros, y si hubo una carga de ese archivo, y si el tamaño de carga actual es exactamente `X-Start-Byte`, entonces agregarle los datos. |
70 | 70 |
|
71 | 71 |
|
72 |
| -Here's the demo with both client and server code, written on Node.js. |
| 72 | +Aquí esta la demostración con el código tanto del cliente como del servidor, escrito en Node.js. |
73 | 73 |
|
74 |
| -It works only partially on this site, as Node.js is behind another server named Nginx, that buffers uploads, passing them to Node.js when fully complete. |
| 74 | +Esto funciona solo parcialmente en este sitio, ya que Node.js esta detrás de otro servidor llamado Nginx, que almacena cargas, pasándolas a Node.js cuando esta completamente lleno. |
75 | 75 |
|
76 |
| -But you can download it and run locally for the full demonstration: |
| 76 | +Pero puedes cargarlo y ejecutarlo localmente para la demostración completa: |
77 | 77 |
|
78 | 78 | [codetabs src="upload-resume" height=200]
|
79 | 79 |
|
80 |
| -As we can see, modern networking methods are close to file managers in their capabilities -- control over headers, progress indicator, sending file parts, etc. |
| 80 | +Como podemos ver, los métodos de red modernos estan cerca de los gestores de archivos en sus capacidades -- control sobre header, indicador de progreso, enviar partes de archivos, etc. |
81 | 81 |
|
82 |
| -We can implement resumable upload and much more. |
| 82 | +Podemos implemetar la carga reanudable y mucho mas. |
0 commit comments