前端分片传递数据给后端

时间:2024-06-03 07:55:03

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}`)
})