前端分片传递数据给后端

html:

<input type="file" id='f' />

 <button>合并</button>

   function upload(blob) {
        var xhr = new XMLHttpRequest()
        xhr.open('POST', '/blob', true)
        xhr.setRequestHeader('Content-Type', 'text/plain')
        xhr.setRequestHeader('File-ID', '15') // 传递文件ID
        xhr.send(blob)
    }

    document.getElementById('f').addEventListener('change', function (e) {
        // 读取文件内容
        const file = event.target.files[0]
        if (file && file.type === "text/plain") {
            const reader = new FileReader()
            reader.onload = function (e) {
                const content = e.target.result
                console.log(content)
            }
            reader.readAsText(file)
        };
        
        // 上传文件内容
        var blob = this.files[0]
        const CHUNK_SIZE = 20
        const SIZE = blob.size
        var start = 0
        var end = CHUNK_SIZE
        while (start < SIZE) {
            upload(blob.slice(start, end))
            start = end
            end = start + CHUNK_SIZE
        }
    }, false);

    document.querySelector('button').onclick = function(){
        var xhr = new XMLHttpRequest()
        xhr.open('POST', '/combine', true)
        xhr.setRequestHeader('File-ID', '15') // 传递文件ID
        xhr.send()
    }

后端(node服务)

const express = require('express') //引用框架
const app = express() //创建服务
const port = 8088 //项目启动端口
const path = require('path')
const bodyParser = require('body-parser')

// 解析文本/plain类型的请求体
app.use(bodyParser.text({ type: 'text/plain' }))

//设置跨域访问
app.all("*", function (req, res, next) {
    //设置允许跨域的域名,*代表允许任意域名跨域
    res.header("Access-Control-Allow-Origin", '*')
    //允许的header类型
    res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With")
    //跨域允许的请求方式 
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS")
    // 可以带cookies
    res.header("Access-Control-Allow-Credentials", true)

    if (req.method == 'OPTIONS') {
        res.sendStatus(200)
    } else {
        next()
    }
})

// 请求页面
app.get("/index", (req, res) => {
    res.sendFile(path.join(__dirname, 'index.html'))
})

// 存储分块数据的对象
const chunks = {}

app.post('/blob', (req, res) => {
    const chunk = req.body
    const fileId = req.headers['file-id']
    if (!chunks[fileId]) {
        chunks[fileId] = []
    }
    chunks[fileId].push(chunk)
    res.send(JSON.stringify({ msg: '接受完毕', data: JSON.stringify(chunk) }))
})
// 处理合并分块后的数据
app.post('/combine', (req, res) => {
    const fileId = req.headers['file-id']
    const data = chunks[fileId].join('')
    // 清除存储的分块数据
    delete chunks[fileId]
    console.log(`文件ID: ${fileId}, 合并后的数据: ${data}`)
    res.send(JSON.stringify({ msg: '分块数据已合并', data: data }))
})

//创建项目
app.listen(port, () => {
    console.log(`项目启动成功-http://localhost:${port}`)
})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值