本地环境 chrome 53 ubuntu
通过查询相关资料得知 chrome 对 blob 有大小限制大约在 500Mb 的样子, 由于上传过程中要对文件内容进行客户端加密(不要问为什么,就是要在客户端层面加密,跟 https 无关,也不要问这个梗为什么). 不然就直接用 webuploader 之类的了,何必自己造轮子。
所以 上传文件就分片, 按 10MB 一个分片, 目前写的代码在传小文件,大约 300Mb 左右的时候正常,但是上传超过 1G 左右文件, 浏览器就直接报错了。
net::ERR_FILE_NOT_FOUND
代码很简单,根据文件大小分片,然后递归调用
测试代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="//
cdn.bootcss.com/jquery/2.2.4/jquery.js"></script>
<script src="
http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body>
<div ng-app="testapp" ng-controller="testctl">
<input type="file" id="file">
<input type="button" ng-click="one()" value="test_split_upload">
</div>
<script>
(function () {
'use strict';
angular
.module('testapp', [
])
.controller('testctl',['$scope','$http','$q',function ($scope,$http,$q) {
$
scope.one = function () {
$scope.file = $('#file').get(0).files[0];
$scope.splitfilea(1);
};
$scope.splitfilea = function (currentpage) {
let persize=1024*1024*10; //10Mb
let allpage = Math.ceil($scope.file.size/persize);
let start = (currentpage-1)*persize;
let end = start+persize;
if(currentpage===allpage){
end=$scope.file.size;
}
$scope.filesplitdata = $scope.file.slice(start, end);
$scope.r = new FileReader();
$scope.r.readAsDataURL($scope.filesplitdata);
$scope.r.onloadend=function (e) {
console.log(currentpage);
var bolb = e.target.result;
$scope.encode_blob = new Blob([bolb]);//这里本来要加密,测试直接创建一个 Blob
$q.when($scope.httppost($scope.encode_blob)).then(function () {
delete $scope.formData;
if(currentpage<=allpage){
currentpage = currentpage+1;
$scope.splitfilea(currentpage);
}else{
console.log('end');
}
});
};
};
$scope.httppost = function (blob) {
var deferral_local = $q.defer();
$http({
method: 'POST',
url: '/test/up4/1.php',
headers: {
'Content-Type': undefined
},
data: {
abc: blob,
filename:"xxxxxxx.txt",
type:"xxxxxx"
},
transformRequest: function (data, headersGetter) {
if(!$scope.formData){
$scope.formData = new FormData();
}
angular.forEach(data, function (value, key) {
if(key === "abc"){
$scope.formData.append(key, value,"xxx.txt");
}else{
$scope.formData.append(key, value);
}
});
var headers = headersGetter();
delete headers['Content-Type'];
return $scope.formData;
}
}).success(function (response) {
deferral_local.resolve( { status: 'good' } );
});
return deferral_local.promise;
};
}]);
}());
</script>
</body>
</html>
服务端: 4.php(暂为空)
<?php
?>
这个上传 1G 左右大文件时会上传大约 40 个分片的时候就报错了.
JS 小白,求大神指点, 估计应该还是 blob 大小限制, 一直不明白的就是我都分片了, 怎么还是超过限制呢?
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.