node文件分片上传

本文使用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>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值