本文使用express+multiparty实现文件的分片上传
//后端
const express=require('express');
const body=require('body-parser')
const multiparty=require('multiparty');
const fse=require('fs-extra');
const path=require('path');
const fs=require('fs')
const app=new express();
app.use(express.static(__dirname+'/public'))
app.use(body.urlencoded({extended:true}))
app.use(body.json())
const PUBLIC_PATH=path.resolve(__dirname,'public/upload')
app.post('/upload',(req,res)=>{
const form=new multiparty.Form({uploadDir:'temp'})//选择上传目录
form.parse(req)
//监听文件上传
form.on('file',async(name,chunk)=>{
//命名文件夹
let chunkDir=`${PUBLIC_PATH}/${chunk.originalFilename.split('.')[0]}`
if(!fse.existsSync(chunkDir)){
await fse.mkdirs(chunkDir)
}
var dPath=path.join(chunkDir,chunk.originalFilename.split('.')[1])
await fse.move(chunk.path,dPath,{overwrite:true})
res.send('文件上传成功');
})
}
)
//合并分片
app.post('/merge',async function(req,res){
var name=req.body.name
var fname=name.split('.')[0]
let chunkDir=path.join(PUBLIC_PATH,fname);
let chunks=await fse.readdir(chunkDir);
chunks.sort((a,b)=>{
a-b;
}).map(chunkPath=>{
//合并文件 fs.appendFileSync(path.join(PUBLIC_PATH,name),fs.readFileSync(`${chunkDir}/${chunkPath}`))
})
//移除分片目录
fse.removeSync(chunkDir);
res.send({merge:'合并成功'})
})
app.listen(4050,()=>{console.log('开启端口')});
//前端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="file">
<button>上传</button>
<script src="axios.js"></script>
<script>
let btn=document.getElementsByTagName('button')[0]
let input=document.getElementsByTagName('input')[0]
var chunkSize=1024*1024 //分片大小,每次1mb
let index=0;
btn.onclick=function(){
let file=input.files[0]
let [fname,fext]=file.name.split('.')
let start=0;
upload(0)
function upload(index){
console.log(index)
start=index*chunkSize
//文件上传完合并
if(start>file.size){
axios.post('/merge',{name:file.name}).then(data=>{console.log(data)})
return;
}
let formdata=new FormData()
let blob=file.slice(start,start+chunkSize)
let blobName=`${fname}.${index}.${fext}`;
let blobFile=new File([blob],blobName)
formdata.append('file',blobFile)
axios.post('/upload',formdata).then(data=>{
console.log(data)
upload(++index)
})
}
}
</script>
</body>
</html>