HTML5 文件上传

本文介绍两种文件上传方式:使用XHR2上传二进制文件和利用HTML5实现的大文件分片上传。前者直接将文件转换为二进制进行上传;后者则通过将大文件切分为多个小片段逐个上传,最终合并成完整文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.XHR2上传二进制文件

html代码:

<input type="file" onchange="handleUpload()">

javascript代码:

function handleUpload()
{
    var file = document.querySelector('input[type=file]').files[0];
    if(!!file) {
        var reader = new FileReader();

        // 读取文件二进制
        reader.readAsArrayBuffer(file);
        reader.onload = function() {
            upload(this.result, file.name);
        }
    }
}

function upload(binary, filename)
{
    var xhr = new XMLHttpRequest();

    // 通过post发送二进制数据,文件信息拼接在url
    xhr.open('POST', './upload.php?filename=' + filename);
    xhr.overrideMimeType("application/octet-stream");

    if(xhr.sendAsBinary) {
        xhr.sendAsBinary(binary);
    }else {
        xhr.send(binary);
    }

    xhr.onload = function() {
        var res = JSON.parse(xhr.response);
        if(res.status === 'success') {
            alert('上传成功');
        }else {
            alert('上传失败');
        }
    }
}

php代码:

<?php

$result = new stdClass();
$fileName = $_GET['filename'];
$filePath = './document/';

function binary_to_file($fileName)
{
    // 获取二进制数据
    $content = file_get_contents('php://input');
    if(empty($content)) {
        $content = $GLOBALS['HTTP_RAW_POST_DATA'];
    }

    $res = file_put_contents($GLOBALS['filePath'] . $fileName, $content, true);
    return $res;
}

if(binary_to_file($fileName) === FALSE) {
    $result->status = 'error';
}else {
    $result->status = 'success';
}

echo json_encode($result);
2.HTML5 大文件分片上传

javascript代码:

const LENGTH = 10*1024;  // 每次上传10kb
var file,
    chunks = [],
    index = 1,   // 当前上传块
    total;       // 总块数

function handleUpload() {
    file = document.querySelector('[type=file]').files[0];
    total = Math.ceil(file.size / LENGTH);

    for(var i = 0; i < total; i++) {
        chunks[i] = file.slice(i*LENGTH, (i+1)*LENGTH);
    }

    upload(chunks, index, total, polling);
}

function upload(chunks, index, total, callback) {
    var xhr = new XMLHttpRequest(),
        chunk = chunks[index - 1],
        formData = new FormData();

    // 表单对象
    formData.append('file', chunk);
    formData.append('index', index);
    formData.append('total', total);
    formData.append('filename', file.name);

    xhr.open('POST', './upload.php');
    xhr.send(formData);

    xhr.onload = function() {
        var res = JSON.parse(xhr.response);
        if(typeof callback == 'function') {
            callback.call(this, res, chunks, index, total);
        }
    }
}

function polling(res, chunks, index, total)
{
    if(res.isFinish) {
        alert('上传成功')
    }else {
        console.log(res.progress);
        upload(chunks, index + 1, total, polling);
    }
}

php代码:

文件上传类 FileUpload.php

<?php

class FileUpload
{
    private $index;
    private $total;
    private $filename;
    private $filePath = './document/';
    private $file;
    private $tmpFile;    // 临时文件

    function __construct($tmpFile, $index, $total, $filename)
    {
        $this->index = $index;
        $this->total = $total;
        $this->filename = $filename;
        $this->tmpFile = $tmpFile;

        $this->move_file();
    }

    /**
     * 创建文件夹
     * @return bool
     */
    public function touch_dir()
    {
        if(!file_exists($this->filePath)) {
            return mkdir($this->filePath);
        }
    }

    /**
     * 移动文件
     */
    public function move_file()
    {
        $this->touch_dir();
        $this->file = $this->filePath . $this->filename . '_' . $this->index;
        move_uploaded_file($this->tmpFile, $this->file);
    }

    /**
     * 合并文件
     */
    public function merge_file()
    {
        if($this->index == $this->total) {
            $mergeFile = $this->filePath . $this->filename;
            for($i = 1; $i <= $this->total; $i++) {
                $chunk = file_get_contents($mergeFile.'_'.$i);
                file_put_contents($mergeFile, $chunk, FILE_APPEND);
            }
            $this->del_file();
        }
    }

    /**
     * 删除文件
     */
    public function del_file()
    {
        for($i = 1; $i <= $this->total; $i++) {
            $delFile = $this->filePath . $this->filename. '_' . $i;
            @unlink($delFile);
        }
    }

    /**
     * 结果返回
     * @return stdClass
     */
    public function getReturn()
    {
        $result = new stdClass();
        if($this->index == $this->total) {
            $result->isFinish = TRUE;
            $this->merge_file();
        }else {
            $result->progess = ($this->index / $this->total);
        }

        return $result;
    }
}

接口调用upload.php

<?php

require './FileUpload.php';

$fileUpload = new FileUpload($_FILES['file']['tmp_name'], $_POST['index'], $_POST['total'], $_POST['filename']);
$result = $fileUpload->getReturn();

echo json_encode($result);
代码来源:http://xxling.com/blog/article/75.aspx 我只是将其代码中asp实例改成了php,转载及使用必须注明原作者。 请遵循原作者开放分享的方式,请勿用来赚取积分!!! 代码做的非常简单,只是用于演示,没有加入任何过滤函数。请务必修改(加入过滤函数)后使用,【坚决不能】直接用于网站!! 之前没怎么接触过js,也是随手做一个。如果不满意请各位多包含,毕竟我不是骗分,也请您高抬贵手。 目前网上看到最好的一个HTML5批量上传程序,它使用纯html+js进行批量上传,不需要flash、jquery等额外组件,大小只有10KB左右。 主要是我想研究一下html5批量上传,但发现纯html5php中会出现超时、没有进度等问题,于是这网上找了一圈。发现目前的代码,要不就是传统的flash,要不就是调用臃肿的jquery,要不就是代码动辄几百K,根本没法分析。而且优快云上资源骗分居多,找了一圈花了几十分,还是没下载到一个真正满意的代码。 于是根据这位博主的分享,把原程序精简,并改为了php脚本。因为我php也是初学,之前一直出现只上传1个文件的问题。后来发现是由于定义秒为文件名,本地速度过快将前面的函数覆盖了。多亏了php的sleep,才将这个问题解决。 于是这个简单的批量上传组件就这样做好了,欢迎各位测试和修改。 最后再次提醒各位务必牢记原作者xiaolingzi和其博客地址地址: http://xxling.com/blog/article/75.aspx 转载请注明原作者,修改和使用也不要去掉js的作者标记。 毕竟那标记就一行,人家写个程序很不容易,请各位尊重作者的劳动。谢谢各位配合!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值