前端切片上传

切片上传

//前端代码
<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');
})



猜你喜欢

转载自blog.csdn.net/weixin_47818125/article/details/125382199