前端切片上传

该博客介绍了如何使用前端JavaScript实现文件切片上传,并结合Node.js后端利用`multiparty`库处理上传的文件片段。前端通过监听按钮点击事件,获取文件并按指定大小进行切片,然后逐片发送到'/upload'接口。后端接收到文件片段后,将其保存在临时目录,并重命名为原文件名。整个过程展示了前端与后端协作处理大文件上传的策略。
摘要由CSDN通过智能技术生成

切片上传

//前端代码
<body>
    <input type="file" id="input">
    <button id="btn">上传</button>

    <script>
        const btn = document.getElementById('btn');
        const input = document.getElementById('input');
        const chunkSize = 1024;
        let index = 0;
        btn.addEventListener('click', upload);

        function upload() {
            const file = input.files[0];
            const [filename, ext] = file.name.split('.')
            console.log(file);

            let start = index * chunkSize;
			//终止条件
            if (start > file.size) return;

            const blob = file.slice(start, start + chunkSize);
            const blobName = `${filename}${index}.${ext}`
            //new  File() new一个文件   文件二进制blob    文件二进制的名字blobName
            const blobFile = new File([blob], blobName)
            //创建一个表单数据
            const formData = new FormData();
			//我们可以通过append(key, value)来添加数据,如果指定的key不存在则会新增一条数据,如果key存在,则添加到数据的末尾
            formData.append('file', blobFile)

            fetch('/upload', {
                method: 'post',
                body: formData
            }).then(() => {
                index++;
                //重复调用
                upload()
            })
        }
    </script>

</body>


//使用node.js模拟后端操作。
const Koa = require('koa');
const Router = require('koa-router');
const server = require('koa-static');
const multiparty = require('multiparty');


const path = require('path');
const fs = require('fs');


const app = new Koa();
const router = new Router();

router.post('/upload', async(ctx) => {
    var form = new multiparty.Form({
        uploadDir: 'temp'
    })

    form.parse(ctx.req);
    form.on('file', (name, file) => {
        const newPath = path.resolve(__dirname, 'temp', file.originalFilename)
        fs.rename(file.path, newPath, (err) => {
            if (err) console.log(err);
        })
        console.log('上传成功');
    })
    ctx.response.body = '请求成功';
})

app.use(router.routes());
app.use(server(path.join(__dirname, '/public')));

app.listen(3000, () => {
    console.log('server listen at port 3000');
})



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值