使用fetch
方法,上传文件非常容易。
如何断线后恢复上传?没有内置选项,但我们可以通过一些方法来实现它。
可恢复上传应该带有上传进度指示,因为我们预计文件很大(如果需要恢复)。所以,由于fetch
不允许跟踪上传进度,我们将使用XMLHttpRequest。
不太有用的进度事件
要恢复上传,我们需要知道在断线前上传了多少数据。
有xhr.upload.onprogress
来跟踪上传进度。
不幸的是,它不能帮助我们在这里恢复上传,因为它在数据发送时触发,但数据是否被服务器接收?浏览器不知道。
也许它被本地网络代理缓冲了,或者也许远程服务器进程刚刚死掉了,无法处理它们,或者它只是在中途丢失了,没有到达接收者。
这就是为什么这个事件只对显示一个漂亮的进度条有用。
要恢复上传,我们需要准确地知道服务器接收了多少字节。只有服务器才能知道这一点,所以我们将发出一个额外的请求。
算法
-
首先,创建一个文件 ID,用于唯一标识我们要上传的文件。
let fileId = file.name + '-' + file.size + '-' + file.lastModified;
这是恢复上传所需的,用于告诉服务器我们正在恢复什么。
如果名称、大小或最后修改日期发生变化,则将会有另一个
fileId
。 -
向服务器发送一个请求,询问它已经有多少字节,如下所示
let response = await fetch('status', { headers: { 'X-File-Id': fileId } }); // The server has that many bytes let startByte = +await response.text();
这假设服务器通过
X-File-Id
标头跟踪文件上传。应该在服务器端实现。如果文件还不存在于服务器上,则服务器响应应为
0
-
然后,我们可以使用
Blob
方法slice
从startByte
发送文件xhr.open("POST", "upload"); // File id, so that the server knows which file we upload xhr.setRequestHeader('X-File-Id', fileId); // The byte we're resuming from, so the server knows we're resuming xhr.setRequestHeader('X-Start-Byte', startByte); xhr.upload.onprogress = (e) => { console.log(`Uploaded ${startByte + e.loaded} of ${startByte + e.total}`); }; // file can be from input.files[0] or another source xhr.send(file.slice(startByte));
在这里,我们将文件 ID 作为
X-File-Id
发送给服务器,以便它知道我们正在上传哪个文件,并将起始字节作为X-Start-Byte
发送,以便它知道我们不是从头开始上传,而是恢复上传。服务器应该检查其记录,如果存在该文件的上传,并且当前上传的大小正好是
X-Start-Byte
,则将数据追加到它。
以下是使用 Node.js 编写的客户端和服务器代码的演示。
它在这个网站上只能部分工作,因为 Node.js 在另一个名为 Nginx 的服务器后面,该服务器缓冲上传,并在完全完成时将它们传递给 Node.js。
但是你可以下载它并在本地运行以获得完整的演示
let http = require('http');
let static = require('node-static');
let fileServer = new static.Server('.');
let path = require('path');
let fs = require('fs');
let debug = require('debug')('example:resume-upload');
let uploads = Object.create(null);
function onUpload(req, res) {
let fileId = req.headers['x-file-id'];
let startByte = +req.headers['x-start-byte'];
if (!fileId) {
res.writeHead(400, "No file id");
res.end();
}
// we'll files "nowhere"
let filePath = '/dev/null';
// could use a real path instead, e.g.
// let filePath = path.join('/tmp', fileId);
debug("onUpload fileId: ", fileId);
// initialize a new 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
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
if (upload.bytesReceived != startByte) {
res.writeHead(400, "Wrong start byte");
res.end(upload.bytesReceived);
return;
}
// append to existing file
fileStream = fs.createWriteStream(filePath, {
flags: 'a'
});
debug("File reopened: " + filePath);
}
req.on('data', function(data) {
debug("bytes received", upload.bytesReceived);
upload.bytesReceived += data.length;
});
// send request body to file
req.pipe(fileStream);
// when the request is finished, and all its data is written
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
res.end("Success " + upload.bytesReceived);
} else {
// connection lost, we leave the unfinished file around
debug("File unfinished, stopped at " + upload.bytesReceived);
res.end();
}
});
// in case of I/O error - finish the request
fileStream.on('error', function(err) {
debug("fileStream error");
res.writeHead(500, "File error");
res.end();
});
}
function onStatus(req, res) {
let fileId = req.headers['x-file-id'];
let upload = uploads[fileId];
debug("onStatus fileId:", fileId, " upload:", upload);
if (!upload) {
res.end("0")
} else {
res.end(String(upload.bytesReceived));
}
}
function accept(req, res) {
if (req.url == '/status') {
onStatus(req, res);
} else if (req.url == '/upload' && req.method == 'POST') {
onUpload(req, res);
} else {
fileServer.serve(req, res);
}
}
// -----------------------------------
if (!module.parent) {
http.createServer(accept).listen(8080);
console.log('Server listening at port 8080');
} else {
exports.accept = accept;
}
class Uploader {
constructor({file, onProgress}) {
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
this.fileId = file.name + '-' + file.size + '-' + file.lastModified;
}
async getUploadedBytes() {
let response = await fetch('status', {
headers: {
'X-File-Id': this.fileId
}
});
if (response.status != 200) {
throw new Error("Can't get uploaded bytes: " + response.statusText);
}
let text = await response.text();
return +text;
}
async upload() {
this.startByte = await this.getUploadedBytes();
let xhr = this.xhr = new XMLHttpRequest();
xhr.open("POST", "upload", true);
// send file id, so that the server knows which file to resume
xhr.setRequestHeader('X-File-Id', this.fileId);
// send the byte we're resuming from, so the server knows we're resuming
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);
xhr.send(this.file.slice(this.startByte));
// return
// true if upload was successful,
// false if aborted
// throw in case of an error
return await new Promise((resolve, reject) => {
xhr.onload = xhr.onerror = () => {
console.log("upload end status:" + xhr.status + " text:" + xhr.statusText);
if (xhr.status == 200) {
resolve(true);
} else {
reject(new Error("Upload failed: " + xhr.statusText));
}
};
// onabort triggers only when xhr.abort() is called
xhr.onabort = () => resolve(false);
});
}
stop() {
if (this.xhr) {
this.xhr.abort();
}
}
}
<!DOCTYPE HTML>
<script src="uploader.js"></script>
<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)">
</form>
<button onclick="uploader.stop()">Stop upload</button>
<div id="log">Progress indication</div>
<script>
function log(html) {
document.getElementById('log').innerHTML = html;
console.log(html);
}
function onProgress(loaded, total) {
log("progress " + loaded + ' / ' + total);
}
let uploader;
document.forms.upload.onsubmit = async function(e) {
e.preventDefault();
let file = this.elements.myfile.files[0];
if (!file) return;
uploader = new Uploader({file, onProgress});
try {
let uploaded = await uploader.upload();
if (uploaded) {
log('success');
} else {
log('stopped');
}
} catch(err) {
console.error(err);
log('error');
}
};
</script>
正如我们所看到的,现代网络方法在功能上接近文件管理器——对标头、进度指示器、发送文件部分等的控制。
我们可以实现可恢复上传等等。
评论
<code>
标签;对于多行代码,请使用<pre>
标签;对于超过10行的代码,请使用沙盒(例如 plnkr,jsbin,codepen…)。