Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 29 additions & 29 deletions 5-network/09-resume-upload/article.md
Original file line number Diff line number Diff line change
@@ -1,82 +1,82 @@
# Resumable file upload

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Importante: o título do artigo ficou sem tradução. Ele aparece no índice e no topo da página, então vale traduzir também. Uma sugestão, mantendo o termo "upload" que você já usa no restante do texto:

Suggested change
# Resumable file upload
# Upload de arquivo retomável


With `fetch` method it's fairly easy to upload a file.
Com o método `fetch` é bem fácil fazer upload de um arquivo.

How to resume the upload after lost connection? There's no built-in option for that, but we have the pieces to implement it.
Como retomar o upload depois de perder a conexão? Não existe nenhuma opção nativa para isso, mas temos as peças para implementá-lo.

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).
Uploads retomáveis devem vir com indicação de progresso de upload, já que esperamos arquivos grandes (se é que podemos precisar retomar). Então, como `fetch` não permite acompanhar o progresso de upload, vamos usar o [XMLHttpRequest](info:xmlhttprequest).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Detalhe (opcional): "se é que podemos precisar retomar" acrescenta um tom de dúvida que o original não tem. Em "(if we may need to resume)", o autor só explica que, com arquivos grandes, talvez seja preciso retomar o envio. Que tal assim?

Suggested change
Uploads retomáveis devem vir com indicação de progresso de upload, já que esperamos arquivos grandes (se é que podemos precisar retomar). Então, como `fetch` não permite acompanhar o progresso de upload, vamos usar o [XMLHttpRequest](info:xmlhttprequest).
Uploads retomáveis devem vir com indicação de progresso de upload, já que esperamos arquivos grandes (que talvez precisem ser retomados). Então, como `fetch` não permite acompanhar o progresso de upload, vamos usar o [XMLHttpRequest](info:xmlhttprequest).


## Not-so-useful progress event
## O evento de progresso nem tão útil assim

To resume upload, we need to know how much was uploaded till the connection was lost.
Para retomar o upload, precisamos saber quanto foi enviado até a conexão ser perdida.

There's `xhr.upload.onprogress` to track upload progress.
Existe o `xhr.upload.onprogress` para acompanhar o progresso de upload.

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.
Infelizmente, isso não vai nos ajudar a retomar o upload aqui, já que ele dispara quando os dados são *enviados*, mas será que eles foram recebidos pelo servidor? O navegador não sabe.

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.
Talvez tenham sido colocados em buffer por um proxy de rede local, ou talvez o processo do servidor remoto tenha simplesmente morrido e não conseguido processá-los, ou foram simplesmente perdidos no meio do caminho e não chegaram ao destinatário.

That's why this event is only useful to show a nice progress bar.
É por isso que esse evento só é útil para mostrar uma boa barra de progresso.

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.
Para retomar o upload, precisamos saber *exatamente* o número de bytes recebidos pelo servidor. E só o servidor pode dizer isso, então vamos fazer uma requisição adicional.

## Algorithm
## Algoritmo

1. First, create a file id, to uniquely identify the file we're going to upload:
1. Primeiro, cria um id de arquivo, para identificar unicamente o arquivo que vamos enviar:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Detalhe (opcional): os passos do algoritmo são instruções ao leitor, e o texto trata o leitor por "você" (por exemplo, "você pode baixá-la"). Então o imperativo fica "crie" em vez de "cria". O mesmo vale para a linha 33: "Envie uma requisição ao servidor..." em vez de "Envia".

Suggested change
1. Primeiro, cria um id de arquivo, para identificar unicamente o arquivo que vamos enviar:
1. Primeiro, crie um id de arquivo, para identificar unicamente o arquivo que vamos enviar:

```js
let fileId = file.name + '-' + file.size + '-' + file.lastModified;
```
That's needed for resume upload, to tell the server what we're resuming.
Isso é necessário para retomar o upload, para dizer ao servidor o que estamos retomando.

If the name or the size or the last modification date changes, then there'll be another `fileId`.
Se o nome, ou o tamanho, ou a data da última modificação mudar, então vai existir outro `fileId`.

2. Send a request to the server, asking how many bytes it already has, like this:
2. Envia uma requisição ao servidor, perguntando quantos bytes ele já tem, assim:
```js
let response = await fetch('status', {
headers: {
'X-File-Id': fileId
}
});

// The server has that many bytes
// O servidor tem essa quantidade de bytes
let startByte = +await response.text();
```

This assumes that the server tracks file uploads by `X-File-Id` header. Should be implemented at server-side.
Isso assume que o servidor rastreia uploads de arquivos pelo cabeçalho `X-File-Id`. Deve ser implementado do lado do servidor.

If the file doesn't yet exist at the server, then the server response should be `0`
Se o arquivo ainda não existir no servidor, então a resposta do servidor deve ser `0`

3. Then, we can use `Blob` method `slice` to send the file from `startByte`:
3. Então, podemos usar o método `slice` de `Blob` para enviar o arquivo a partir de `startByte`:
```js
xhr.open("POST", "upload");

// File id, so that the server knows which file we upload
// Id do arquivo, para que o servidor saiba qual arquivo estamos enviando
xhr.setRequestHeader('X-File-Id', fileId);

// The byte we're resuming from, so the server knows we're resuming
// O byte a partir do qual estamos retomando, para que o servidor saiba que estamos retomando
xhr.setRequestHeader('X-Start-Byte', startByte);

xhr.upload.onprogress = (e) => {
console.log(`Uploaded ${startByte + e.loaded} of ${startByte + e.total}`);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Detalhe (opcional): o texto deste console.log ficou em inglês, enquanto o mesmo trecho em uploader.js foi traduzido. Como textos dentro do código podem ser traduzidos, fica mais coerente assim:

Suggested change
console.log(`Uploaded ${startByte + e.loaded} of ${startByte + e.total}`);
console.log(`Enviado ${startByte + e.loaded} de ${startByte + e.total}`);

};

// file can be from input.files[0] or another source
// o arquivo pode vir de input.files[0] ou outra fonte
xhr.send(file.slice(startByte));
```

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.
Aqui enviamos ao servidor tanto o id do arquivo como `X-File-Id`, para que ele saiba qual arquivo estamos enviando, quanto o byte inicial como `X-Start-Byte`, para que ele saiba que não estamos enviando pela primeira vez, mas retomando.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Detalhe (opcional): como "tanto ... como" também é um par correlativo em português, a frase pode ser lida como "tanto o id do arquivo quanto o X-File-Id", e o "quanto" seguinte fica sem par. A ideia do original é que cada informação vai em um cabeçalho. Uma sugestão para evitar a ambiguidade:

Suggested change
Aqui enviamos ao servidor tanto o id do arquivo como `X-File-Id`, para que ele saiba qual arquivo estamos enviando, quanto o byte inicial como `X-Start-Byte`, para que ele saiba que não estamos enviando pela primeira vez, mas retomando.
Aqui enviamos ao servidor o id do arquivo no cabeçalho `X-File-Id`, para que ele saiba qual arquivo estamos enviando, e o byte inicial no cabeçalho `X-Start-Byte`, para que ele saiba que não estamos enviando pela primeira vez, mas retomando.


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.
O servidor deve checar seus registros, e se já houve um upload desse arquivo, e o tamanho atualmente enviado é exatamente `X-Start-Byte`, então acrescentar os dados a ele.


Here's the demo with both client and server code, written on Node.js.
Aqui está a demo com o código tanto do cliente quanto do servidor, escrita em Node.js.

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.
Ela funciona só parcialmente neste site, já que o Node.js está atrás de outro servidor chamado Nginx, que coloca os uploads em buffer, passando-os para o Node.js quando totalmente completos.

But you can download it and run locally for the full demonstration:
Mas você pode baixá-la e rodar localmente para a demonstração completa:

[codetabs src="upload-resume" height=200]

As we can see, modern networking methods are close to file managers in their capabilities -- control over headers, progress indicator, sending file parts, etc.
Como podemos ver, os métodos de rede modernos estão próximos de gerenciadores de arquivos em suas capacidades -- controle sobre cabeçalhos, indicador de progresso, envio de partes do arquivo, etc.

We can implement resumable upload and much more.
Podemos implementar upload retomável e muito mais.
14 changes: 7 additions & 7 deletions 5-network/09-resume-upload/upload-resume.view/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@

<form name="upload" method="POST" enctype="multipart/form-data" action="/upload">
<input type="file" name="myfile">
<input type="submit" name="submit" value="Upload (Resumes automatically)">
<input type="submit" name="submit" value="Enviar (Retoma automaticamente)">
</form>

<button onclick="uploader.stop()">Stop upload</button>
<button onclick="uploader.stop()">Parar upload</button>


<div id="log">Progress indication</div>
<div id="log">Indicação de progresso</div>

<script>
function log(html) {
Expand All @@ -19,7 +19,7 @@
}

function onProgress(loaded, total) {
log("progress " + loaded + ' / ' + total);
log("progresso " + loaded + ' / ' + total);
}

let uploader;
Expand All @@ -36,14 +36,14 @@
let uploaded = await uploader.upload();

if (uploaded) {
log('success');
log('sucesso');
} else {
log('stopped');
log('parado');
}

} catch(err) {
console.error(err);
log('error');
log('erro');
}
};

Expand Down
32 changes: 16 additions & 16 deletions 5-network/09-resume-upload/upload-resume.view/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,40 +13,40 @@ function onUpload(req, res) {
let startByte = +req.headers['x-start-byte'];

if (!fileId) {
res.writeHead(400, "No file id");
res.writeHead(400, "Sem id de arquivo");
res.end();
}

// we'll files "nowhere"
// vamos "descartar" os arquivos
let filePath = '/dev/null';
// could use a real path instead, e.g.
// poderíamos usar um caminho real em vez disso, por exemplo
// let filePath = path.join('/tmp', fileId);

debug("onUpload fileId: ", fileId);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Detalhe (opcional): as mensagens de depuração (debug(...)) deste arquivo continuaram em inglês, enquanto o console.log da linha 120 foi traduzido. Ficaram assim as linhas 25, 41, 53, 58, 68, 76 e 83 (por exemplo, "New file created", "File reopened", "Upload finished", "File unfinished, stopped at", "fileStream error"). Se a ideia for traduzir os textos do exemplo, vale incluir essas também, sempre mantendo os nomes de variáveis como fileId e bytesReceived.


// initialize a new upload
// inicializa um novo upload
if (!uploads[fileId]) uploads[fileId] = {};
let upload = uploads[fileId];

debug("bytesReceived:" + upload.bytesReceived + " startByte:" + startByte)

let fileStream;

// if startByte is 0 or not set, create a new file, otherwise check the size and append to existing one
// se startByte for 0 ou não estiver definido, cria um novo arquivo, caso contrário checa o tamanho e acrescenta ao existente
if (!startByte) {
upload.bytesReceived = 0;
fileStream = fs.createWriteStream(filePath, {
flags: 'w'
});
debug("New file created: " + filePath);
} else {
// we can check on-disk file size as well to be sure
// também podemos checar o tamanho do arquivo em disco para ter certeza
if (upload.bytesReceived != startByte) {
res.writeHead(400, "Wrong start byte");
res.writeHead(400, "Byte inicial incorreto");
res.end(upload.bytesReceived);
return;
}
// append to existing file
// acrescenta ao arquivo existente
fileStream = fs.createWriteStream(filePath, {
flags: 'a'
});
Expand All @@ -59,29 +59,29 @@ function onUpload(req, res) {
upload.bytesReceived += data.length;
});

// send request body to file
// envia o corpo da requisição para o arquivo
req.pipe(fileStream);

// when the request is finished, and all its data is written
// quando a requisição termina, e todos os seus dados são escritos
fileStream.on('close', function() {
if (upload.bytesReceived == req.headers['x-file-size']) {
debug("Upload finished");
delete uploads[fileId];

// can do something else with the uploaded file here
// podemos fazer outra coisa com o arquivo enviado aqui

res.end("Success " + upload.bytesReceived);
res.end("Sucesso " + upload.bytesReceived);
} else {
// connection lost, we leave the unfinished file around
// conexão perdida, deixamos o arquivo inacabado por aí
debug("File unfinished, stopped at " + upload.bytesReceived);
res.end();
}
});

// in case of I/O error - finish the request
// em caso de erro de I/O - termina a requisição
fileStream.on('error', function(err) {
debug("fileStream error");
res.writeHead(500, "File error");
res.writeHead(500, "Erro de arquivo");
res.end();
});

Expand Down Expand Up @@ -117,7 +117,7 @@ function accept(req, res) {

if (!module.parent) {
http.createServer(accept).listen(8080);
console.log('Server listening at port 8080');
console.log('Servidor escutando na porta 8080');
} else {
exports.accept = accept;
}
26 changes: 13 additions & 13 deletions 5-network/09-resume-upload/upload-resume.view/uploader.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ class Uploader {
this.file = file;
this.onProgress = onProgress;

// create fileId that uniquely identifies the file
// we could also add user session identifier (if had one), to make it even more unique
// cria o fileId que identifica unicamente o arquivo
// também poderíamos adicionar um identificador de sessão do usuário (se tivéssemos um), para deixar ainda mais único
this.fileId = file.name + '-' + file.size + '-' + file.lastModified;
}

Expand All @@ -17,7 +17,7 @@ class Uploader {
});

if (response.status != 200) {
throw new Error("Can't get uploaded bytes: " + response.statusText);
throw new Error("Não foi possível obter os bytes enviados: " + response.statusText);
}

let text = await response.text();
Expand All @@ -31,35 +31,35 @@ class Uploader {
let xhr = this.xhr = new XMLHttpRequest();
xhr.open("POST", "upload", true);

// send file id, so that the server knows which file to resume
// envia o id do arquivo, para que o servidor saiba qual arquivo retomar
xhr.setRequestHeader('X-File-Id', this.fileId);
// send the byte we're resuming from, so the server knows we're resuming
// envia o byte a partir do qual estamos retomando, para que o servidor saiba que estamos retomando
xhr.setRequestHeader('X-Start-Byte', this.startByte);

xhr.upload.onprogress = (e) => {
this.onProgress(this.startByte + e.loaded, this.startByte + e.total);
};

console.log("send the file, starting from", this.startByte);
console.log("enviando o arquivo, a partir de", this.startByte);
xhr.send(this.file.slice(this.startByte));

// return
// true if upload was successful,
// false if aborted
// throw in case of an error
// retorna
// true se o upload foi bem-sucedido,
// false se foi abortado
// lança um erro em caso de falha
return await new Promise((resolve, reject) => {

xhr.onload = xhr.onerror = () => {
console.log("upload end status:" + xhr.status + " text:" + xhr.statusText);
console.log("status final do upload:" + xhr.status + " texto:" + xhr.statusText);

if (xhr.status == 200) {
resolve(true);
} else {
reject(new Error("Upload failed: " + xhr.statusText));
reject(new Error("Falha no upload: " + xhr.statusText));
}
};

// onabort triggers only when xhr.abort() is called
// onabort só dispara quando xhr.abort() é chamado
xhr.onabort = () => resolve(false);

});
Expand Down