Resumable.js 基于 HTML5 File API 多文件上传插件

发布于 2018-06-13 23:32:11 字数 10634 浏览 3450 评论 0

Resumable.js 是一个 JavaScript 文件上传插件,基于 HTML5 File API 接口编写,可提供一个稳定的、可恢复的、简单易用的多文件上传插件。

通俗来讲 Resumable.js 支持断点续传,这是 Resumable.js 的一大亮点,Resumable.js 预先将大文件切割成多个小文件,然后分片上传,如果上传失败将重新上传,直到最后所有文件均上传完成,同时该插件还支持用户暂停、恢复甚至恢复上传而不丢失状态。

项目地址:http://www.resumablejs.com/

使用方法

创建一个新的可恢复对象,该对象具有什么和在何处发布的信息:

var r = new Resumable({
  target:'/api/photo/redeem-upload-token', 
  query:{upload_token:'my_token'}
});
// Resumable.js isn't supported, fall back on a different method
if(!r.support) location.href = '/some-old-crappy-uploader';

为了允许文件被选择和拖放,您将指定要删除的目标和DOM项目以供浏览:

r.assignBrowse(document.getElementById('browseButton'));
r.assignDrop(document.getElementById('dropTarget'));

在这之后,与 Resumable.js 的交互是通过听事件来完成的:

r.on('fileAdded', function(file){});
r.on('fileSuccess', function(file,message){});
r.on('fileError', function(file, message){});

服务端代码

在用户浏览器中出现了大部分用于恢复的魔术。但是文件仍然需要从服务器端的块重新组合。这应该是一个相当简单的任务,可以在任何能够接收文件上传的Web框架或语言中实现。

要处理上载块的状态,多个额外参数连同所有请求一起发送:

  • resumableChunkNumber: The index of the chunk in the current upload. First chunk is 1 (no base–0 counting here).
  • resumableChunkSize: The general chunk size. Using this value and resumableTotalSize you can calculate the total number of chunks. Please note that the size of the data received in the HTTP might be lower than resumableChunkSize of this for the last chunk for a file.
  • resumableTotalSize: The total file size.
  • resumableIdentifier: A unique identifier for the file contained in the request.
  • resumableFilename: The original file name (since a bug in Firefox results in the file name not being transmitted in chunk multipart posts).
  • resumableRelativePath: The file’s relative path when selecting a directory (defaults to file name in all browsers except Chrome).

You should allow for the same chunk to be uploaded more than once; this isn’t standard behaviour, but on an unstable network environment it could happen, and this case is exactly what Resumable.js is designed for.

For every request, you can confirm reception in HTTP status codes:

  • 200: The chunk was accepted and correct. No need to re-upload.
  • 415. 500, 501: The file for which the chunk was uploaded is not supported, cancel the entire upload (in fact, any >=400 HTTP status code will trigger this result, see details.
  • Anything else: Something went wrong, but try reuploading the file.

Handling GET (or test() requests)

This will allow uploads to be resumed after browser restarts and even across browsers (in theory you could even run the same file upload across multiple tabs or different browsers). The POST data requests listed are required to use Resumable.js to receive data, but you can extend support by implementing a corresponding GET request with the same parameters:

  • If this request returns a 200 HTTP code, the chunks is assumed to have been completed.
  • If the request returns anything else, the chunk will be uploaded in the standard fashion.

API 文档

Resumable

配置参数

The object is loaded with a configuation hash:

var r = new Resumable({opt1:'val', ...});

Available configuration options are:

  • target The target URL for the multipart POST request (Default: /)
  • chunkSize The size in bytes of each uploaded chunk of data (Default: 1*1024*1024)
  • simultaneousUploads Number of simultaneous uploads (Default: 3)
  • fileParameterName The name of the multipart POST parameter to use for the file chunk (Default: file)
  • query Extra parameters to include in the multipart POST with data. This can be an object or a function. If a function, it will be passed a ResumableFile object (Default: {})
  • headers Extra headers to include in the multipart POST with data (Default: {})
  • prioritizeFirstAndLastChunk Prioritize first and last chunks of all files. This can be handy if you can determine if a file is valid for your service from only the first or last chunk. For example, photo or video meta data is usually located in the first part of a file, making it easy to test support from only the first chunk. (Default: false)
  • testChunks Make a GET request to the server for each chunks to see if it already exists. If implemented on the server-side, this will allow for upload resumes even after a browser crash or even a computer restart. (Default: true)
  • generateUniqueIdentifier Override the function that generates unique identifiers for each file. (Default: null)
  • maxFiles Indicates how many files can be uploaded in a single session. Valid values are any positive integer and undefined for no limit. (Default: undefined)
  • maxFilesErrorCallback A function which displays the please upload n file(s) at a time message. (Default: displays an alert box with the message Please n one file(s) at a time.)

Properties

  • .support A boolean value indicator whether or not Resumable.js is supported by the current browser.
  • .opts A hash object of the configuration of the Resumable.js instance.
  • .files An array of ResumableFile file objects added by the user (see full docs for this object type below).

Methods

  • .assignBrowse(domNodes, isDirectory) Assign a browse action to one or more DOM nodes. Pass in true to allow directories to be selected (Chrome only).
  • .assignDrop(domNodes) Assign one or more DOM nodes as a drop target.
  • .on(event, callback) Listen for event from Resumable.js (see below)
  • .upload() Start or resume uploading.
  • .pause() Pause uploading.
  • .cancel() Cancel upload of all ResumableFile objects and remove them from the list.
  • .progress() Returns a float between 0 and 1 indicating the current upload progress of all files.
  • .isUploading() Returns a boolean indicating whether or not the instance is currently uploading anything.
  • .removeFile(file) Cancel upload of a specific ResumableFile object on the list from the list.
  • .getFromUniqueIdentifier(uniqueIdentifier) Look up a ResumableFile object by its unique identifier.
  • .getSize() Returns the total size of the upload in bytes.

Events

  • .fileSuccess(file) A specific file was completed.
  • .fileProgress(file) Uploading progressed for a specific file.
  • .fileAdded(file) A new file was added.
  • .fileRetry(file) Something went wrong during upload of a specific file, uploading is being retried.
  • .fileError(file, message) An error occured during upload of a specific file.
  • .complete() Uploading completed.
  • .progress() Uploading progress.
  • .error(message, file) An error, including fileError, occured.
  • .pause() Uploading was paused.
  • .cancel() Uploading was canceled.
  • .catchAll(event, ...) Listen to all the events listed above with the same callback function.

ResumableFile

Properties

  • .resumableObj A back-reference to the parent Resumable object.
  • .file The correlating HTML5 File object.
  • .fileName The name of the file.
  • .relativePath The relative path to the file (defaults to file name if relative path doesn’t exist)
  • .size Size in bytes of the file.
  • .uniqueIdentifier A unique identifier assigned to this file object. This value is included in uploads to the server for reference, but can also be used in CSS classes etc when building your upload UI.
  • .chunks An array of ResumableChunk items. You shouldn’t need to dig into these.

Methods

  • .progress(relative) Returns a float between 0 and 1 indicating the current upload progress of the file. If relative is true, the value is returned relative to all files in the Resumable.js instance.
  • .abort() Abort uploading the file.
  • .cancel() Abort uploading the file and delete it from the list of files to upload.
  • .retry() Retry uploading the file.
  • .bootstrap() Rebuild the state of a ResumableFile object, including reassigning chunks and XMLHttpRequest instances.

其他可替代方案

This library is explicitly designed for modern browsers supporting advanced HTML5 file features, and the motivation has been to provide stable and resumable support for large files (allowing uploads of several GB files through HTTP in a predictable fashion).

If your aim is just to support progress indications during upload/uploading multiple files at once, Resumable.js isn’t for you. In those cases, SWFUpload and Plupload provides the same features with wider browser support.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

JSmiles

生命进入颠沛而奔忙的本质状态,并将以不断告别和相遇的陈旧方式继续下去。

0 文章
0 评论
84960 人气
更多

推荐作者

遂心如意

文章 0 评论 0

5513090242

文章 0 评论 0

巷雨优美回忆

文章 0 评论 0

junpengz2000

文章 0 评论 0

13郎

文章 0 评论 0

qq_xU4RDg

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文