GithubHelp home page GithubHelp logo

breakpoint's Introduction

javascript 分片上传文件demo

文件上传是一个使用频率非常高的一个功能。但是项目中总觉得它不够完善。从而暴露出一些细节问题。于是动手写一个分片上传的demo分享出来供大家参考。

实现方式

  • JavaScript有个slice函数可以截取文件指定片段大小,然后把文件写入FormData,与普通的 Ajax 相比,使用 FormData 的最大优点就是我们可以异步上传二进制文件。
$.ajax({
    url: '/upload',
    type: 'POST',
    cache: false,
    data: FormData, 
    processData: false,
    contentType: false 
}).done(function(res) {
}).fail(function(res) {});

processData设置为false。因为data值是FormData对象,不需要对数据做处理。 contentType设置为false。因为是由<form>表单构造的FormData对象,且已经声明了属性enctype="multipart/form-data",所以这里设置为false

  • 上传过程中把分片信息存储到LocalStorage。还有一种方式是,上传时到服务器去看有没有这个文件,再取回大小。根据这个大小找到当前未上传完的文件的起始位置。当前demo主要用第一种方式实现。
  • 服务端用PHP来实现。php的file_put_contents()函数可以追加写入文件。第一个参数为写入路径,第二个为文件,第三个参数FILE_APPEND可以追加写入。具体使用查看:http://php.net/manual/zh/function.file-put-contents.php

目录结构

|-breakpoint
|_____static
|      |___common.js 上传逻辑
|      |__style.css 模板基本样式
|_____upload 附件目录
|
|_____demo.html 模板
|
|_____fileTest.php 服务端文件

使用方法

  • 下载或clone下来,访问/demo.html即可。
  • 初始化,commo.js里已有。
//初始化
UP.__init({
    myFile: "#myFile", //fileinput节点
    ServerUrl:"/fileTest.php",//服务器地址
    eachSize:1024 //分片大小
});

下载地址

https://github.com/wangwenfan/breakpoint

breakpoint's People

Contributors

wangwenfan avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.