HTML5 文档域+FileReader 分段载入文档并提交到服务

日期:2021-01-19 类型:科技新闻 

关键词:公众号小程序,小程序正规价格表,微信群签到小程序,网络抽签小程序,个人做小程序需要什么

表明:应用Ajax方法提交,文档不可以过大,最好是小于34百兆,由于过量的持续Ajax恳求会使后台管理奔溃,获得InputStream中数据信息会为空,特别在Google访问器检测全过程中。

1.简易分段载入文档为Blob,ajax提交到服务器

<div class="container">
    <div class="panel panel-default">
        <div class="panel-heading">分段载入文档:</div>
        <div class="panel-body">
            <input type="file" id="file" />
            <blockquote style="word-break:break-all;"></blockquote>
        </div>
    </div>
</div>

JS:

/*
* 分段载入文档为blob ,并应用ajax提交到服务器
* 分段提交exe文档会抛出出现异常
*/
var fileBox = document.getElementById('file');
file.onchange = function () {
    //获得文档目标
    var file = this.files[0];
    var reader = new FileReader();
    var step = 1024 * 1024;
    var total = file.size;
    var cuLoaded = 0;
    console.info("文档尺寸:" + file.size);
    var startTime = new Date();
    //载入1段取得成功
    reader.onload = function (e) {
        //解决载入的結果
        var loaded = e.loaded;
        //将分段数据信息提交到服务器
        uploadFile(reader.result, cuLoaded, function () {
            console.info('loaded:' + cuLoaded + 'current:' + loaded);
            //假如沒有读完,再次
            cuLoaded += loaded;
            if (cuLoaded < total) {
                readBlob(cuLoaded);
            } else {
                console.log('一共用时:' + (new Date().getTime() - startTime.getTime()) / 1000);
                cuLoaded = total;
            }
        });
    }
    //特定刚开始部位,分层载入文档
    function readBlob(start) {
        //特定刚开始部位和完毕部位载入文档
        //console.info('start:' + start);
        var blob = file.slice(start, start + step);
        reader.readAsArrayBuffer(blob);
    }
    //刚开始载入
    readBlob(0);
    //重要编码提交到服务器
    function uploadFile(result, startIndex, onSuccess) {
        var blob = new Blob([result]);
        //递交到服务器
        var fd = new FormData();
        fd.append('file', blob);
        fd.append('filename', file.name);
        fd.append('loaded', startIndex);
        var xhr = new XMLHttpRequest();
        xhr.open('post', '../ashx/upload2.ashx', true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                // var data = eval('(' + xhr.responseText + ')');
                console.info(xhr.responseText);
                if (onSuccess)
                    onSuccess();
            }
        }
        //刚开始推送
        xhr.send(fd);
    }
}

后台管理编码:
 

/// <summary>
/// upload2 的引言表明
/// </summary>
public class upload2 : IHttpHandler
{
    LogHelper.LogHelper _log = new LogHelper.LogHelper();
    int totalCount = 0;
    public void ProcessRequest(HttpContext context)
    {
        HttpContext _Context = context;
        //接受文档
        HttpRequest req = _Context.Request;
        if (req.Files.Count <= 0)
        {
            WriteStr("获得服务器提交文档不成功");
            return;
        }
        HttpPostedFile _file = req.Files[0];
        //获得主要参数
        // string ext = req.Form["extention"];
        string filename = req.Form["filename"];
        //假如是int 种类当文档大的情况下会出难题 最大也便是 1.9999999990686774G
        int loaded = Convert.ToInt32(req.Form["loaded"]);
        totalCount += loaded;

        string newname = @"F:\JavaScript_Solution\H5Solition\H5Solition\Content\TempFile\";
        newname += filename;
        //接受2级制数据信息并储存
        Stream stream = _file.InputStream;
        if (stream.Length <= 0)
            throw new Exception("接受的数据信息不可以为空");
        byte[] dataOne = new byte[stream.Length];
        stream.Read(dataOne, 0, dataOne.Length);
        FileStream fs = new FileStream(newname, FileMode.Append, FileAccess.Write, FileShare.Read, 1024);
        try
        {
            fs.Write(dataOne, 0, dataOne.Length);
        }
        finally
        {
            fs.Close();
            stream.Close();
        }
        _log.WriteLine((totalCount + dataOne.Length).ToString());
        WriteStr("分段数据信息储存取得成功");
    }
    private void WriteStr(string str)
    {
        HttpContext.Current.Response.Write(str); 
    }
    public bool IsReusable
    {
        get
        {
            return true;
        }
    }

2.分段载入文档为blob ,并应用ajax提交到服务器,追加中断、再次作用实际操作

<div class="container">
    <div class="panel panel-default">
        <div class="panel-heading">分段载入文档:</div>
        <div class="panel-body">
            <input type="file" id="file" />
            <br />
            <input type="button" value="中断" onclick="stop();" />&emsp;
            <input type="button" value="再次" onclick="containue();" />
            <br />
            <progress id="progressOne" max="100" value="0" style="width:400px;"></progress>
            <blockquote id="Status" style="word-break:break-all;"></blockquote>
        </div>
    </div>
</div>

JS:

/*
* 分段载入文档为blob ,并应用ajax提交到服务器
* 应用Ajax方法递交提交数据信息文档尺寸应当比较有限值,最好是500MB之内
* 缘故短期内过量的ajax恳求,Asp.Net后台管理会奔溃获得提交的分层数据信息为空
* 替代方法,长联接或WebSocket
*/
var fileBox = document.getElementById('file');
var reader = null;  //载入实际操作目标
var step = 1024 * 1024 * 3.5;  //每次载入文档尺寸
var cuLoaded = 0; //当今早已载入总数
var file = null; //当今载入的文档目标
var enableRead = true;//标志是不是能够载入文档
fileBox.onchange = function () {
    //获得文档目标
    file = this.files[0];
    var total = file.size;
    console.info("文档尺寸:" + file.size);
    var startTime = new Date();
    reader = new FileReader();
    //载入1段取得成功
    reader.onload = function (e) {
        //解决载入的結果
        var result = reader.result;
        var loaded = e.loaded;
        if (enableRead == false)
            return false;
        //将分段数据信息提交到服务器
        uploadFile(result, cuLoaded, function () {
            console.info('loaded:' + cuLoaded + '----current:' + loaded);
            //假如沒有读完,再次
            cuLoaded += loaded;
            if (cuLoaded < total) {
                readBlob(cuLoaded);
            } else {
                console.log('一共用时:' + (new Date().getTime() - startTime.getTime()) / 1000);
                cuLoaded = total;
            }
            //显示信息結果进度
            var percent = (cuLoaded / total) * 100;
            document.getElementById('Status').innerText = percent;
            document.getElementById('progressOne').value = percent;
        });
    }
    //刚开始载入
    readBlob(0);
    //重要编码提交到服务器
    function uploadFile(result, startIndex, onSuccess) {
        var blob = new Blob([result]);
        //递交到服务器
        var fd = new FormData();
        fd.append('file', blob);
        fd.append('filename', file.name);
        fd.append('loaded', startIndex);
        var xhr = new XMLHttpRequest();
        xhr.open('post', '../ashx/upload2.ashx', true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                if (onSuccess)
                    onSuccess();
            } else if (xhr.status == 500) {
                //console.info('恳求错误,' + xhr.responseText);
                setTimeout(function () {
                    containue();
                }, 1000);
            }
        }
        //刚开始推送
        xhr.send(fd);
    }
}
//特定刚开始部位,分层载入文档
function readBlob(start) {
    //特定刚开始部位和完毕部位载入文档
    var blob = file.slice(start, start + step);
    reader.readAsArrayBuffer(blob);
}
//中断
function stop() {
    //中断载入实际操作
    console.info('中断,cuLoaded:' + cuLoaded);
    enableRead = false;
    reader.abort();
}
//再次
function containue() {
    console.info('再次,cuLoaded:' + cuLoaded);
    enableRead = true;
    readBlob(cuLoaded);
}

后台管理编码同上

3.分段载入文档为2进制数字能量数组 ,并应用ajax提交到服务器

 应用2进制数字能量数组传送的方法,高效率非常低,最后文档还与初始尺寸一些误差

HTML內容同上

JS:

/*
    * 分段载入文档为2进制数字能量数组 ,并应用ajax提交到服务器
    * 应用2进制数字能量数组传送的方法,高效率非常低,最后文档还与初始尺寸一些误差
    */
var fileBox = document.getElementById('file');
var reader = new FileReader(); //载入实际操作目标
var step = 1024 * 1024;  //每次载入文档尺寸
var cuLoaded = 0; //当今早已载入总数
var file = null; //当今载入的文档目标
var enableRead = true;//标志是不是能够载入文档
fileBox.onchange = function () {
    //获得文档目标
    if (file == null) //假如取值数次会有遗失数据信息的将会
        file = this.files[0];
    var total = file.size;
    console.info("文档尺寸:" + file.size);
    var startTime = new Date();
    //载入1段取得成功
    reader.onload = function (e) {
        //解决载入的結果
        var result = reader.result;
        var loaded = e.loaded;
        if (enableRead == false)
            return false;
        //将分段数据信息提交到服务器
        uploadFile(result, cuLoaded, function () {
            console.info('loaded:' + cuLoaded + '----current:' + loaded);
            //假如沒有读完,再次
            cuLoaded += loaded;
            if (cuLoaded < total) {
                readBlob(cuLoaded);
            } else {
                console.log('一共用时:' + (new Date().getTime() - startTime.getTime()) / 1000);
                cuLoaded = total;
            }
            //显示信息結果进度
            var percent = (cuLoaded / total) * 100;
            document.getElementById('Status').innerText = percent;
            document.getElementById('progressOne').value = percent;
        });
    }
    //刚开始载入
    readBlob(0);
    //重要编码提交到服务器
    function uploadFile(result, startIndex, onSuccess) {
        var array = new Int8Array(result);
        console.info(array.byteLength);
        //递交到服务器
        var fd = new FormData();
        fd.append('file', array);
        fd.append('filename', file.name);
        fd.append('loaded', startIndex);
        var xhr = new XMLHttpRequest();
        xhr.open('post', '../ashx/upload3.ashx', true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                // console.info(xhr.responseText);
                if (onSuccess)
                    onSuccess();
            } else if (xhr.status == 500) {
                console.info('服务器错误');
                reader.abort();
            }
        }
        //刚开始推送
        xhr.send(fd);
    }
}
//特定刚开始部位,分层载入文档
function readBlob(start) {
    //特定刚开始部位和完毕部位载入文档
    var blob = file.slice(start, start + step);
    reader.readAsArrayBuffer(blob);
}
//中断
function stop() {
    //中断载入实际操作
    console.info('中断,cuLoaded:' + cuLoaded);
    enableRead = false;
    reader.abort();
}
//再次
function containue() {
    console.info('再次,cuLoaded:' + cuLoaded);
    enableRead = true;
    readBlob(cuLoaded);
}

后台管理编码:

/// <summary>
/// upload3 的引言表明
/// </summary>
public class upload3 : IHttpHandler
{
    LogHelper.LogHelper _log = new LogHelper.LogHelper();
    int totalCount = 0;
    public void ProcessRequest(HttpContext context)
    {
        HttpContext _Context = context;
        //接受文档
        HttpRequest req = _Context.Request;
        string data = req.Form["file"];
        //变换方法1
        //int[] intData = data.Split(',').Select(q => Convert.ToInt32(q)).ToArray();
        //byte[] dataArray = intData.ToList().ConvertAll(x=>(byte)x).ToArray();
        //变换方法2
        byte[] dataArray = data.Split(',').Select(q => int.Parse(q)).Select(q => (byte)q).ToArray();
        //获得主要参数
        string filename = req.Form["filename"];
        //假如是int 种类当文档大的情况下会出难题 最大也便是 1.9999999990686774G
        int loaded = Convert.ToInt32(req.Form["loaded"]);
        totalCount += loaded;
        string newname = @"F:\JavaScript_Solution\H5Solition\H5Solition\Content\TempFile\";
        newname += filename;
        try
        {
            // 接受2级制数据信息并储存
            byte[] dataOne = dataArray;
            FileStream fs = new FileStream(newname, FileMode.Append, FileAccess.Write, FileShare.Read, 1024);
            try
            {
                fs.Write(dataOne, 0, dataOne.Length);
            }
            finally
            {
                fs.Close();
            }
            _log.WriteLine((totalCount + dataOne.Length).ToString());
            WriteStr("分段数据信息储存取得成功");
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    private void WriteStr(string str)
    {
        HttpContext.Current.Response.Write(str);
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

总结

以上所述是网编给大伙儿详细介绍的HTML5 文档域+FileReader 分段载入文档并提交到服务器,期待对大伙儿有一定的协助,假如大伙儿有任何疑惑请给我留言,网编会立即回应大伙儿的。在此也十分谢谢大伙儿对脚本制作之家网站的适用!