VUE 分片上传大文件
前端参考:https://gitee.com/GaoWeiQiang1996/element-chunk-upload
上述开源项目在上传超过2.5G的文件的时候 前端会报错,经过排查发现是获取文件md5的方法出问题导致的,故针对大文件获取md5也需要分片获取,
得知原因后对获取大文件md5的方法做了修改,修改后方法如下:
import SparkMD5 from 'spark-md5'
//获取文件MD5
function getFileMD5(file) {
return new Promise((resolve, reject) => {
let that = this
var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
chunkSize = 2097152*100, // Read in chunks of 200MB
chunks = Math.ceil(file.size / chunkSize),
currentChunk = 0,
spark = new SparkMD5.ArrayBuffer(),
fileReader = new FileReader()
fileReader.onload = function (e) {
console.log('read chunk nr', currentChunk + 1, 'of', chunks)
spark.append(e.target.result) // Append array buffer
currentChunk++
if (currentChunk < chunks) {
loadNext()
} else {
resolve(spark.end())
}
}
fileReader.onerror = function () {
reject("")
}
function loadNext () {
var start = currentChunk * chunkSize,
end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize
fileReader.readAsArrayBuffer(blobSlice.call(file, start, end))
}
loadNext()
})
}
PHP后端接收分片代码如下:
$postData = $request->post();
$filename = base_path() . '/'.$postData['filename'];//确定上传的文件名
file_put_contents("uploadpath",$filename);
//第一次上传时没有文件,就创建文件,此后上传只需要把数据追加到此文件中
if(!file_exists($filename)){
move_uploaded_file($_FILES['file']['tmp_name'], $filename);
}else{
file_put_contents($filename, file_get_contents($_FILES['file']['tmp_name']),FILE_APPEND);
}