大文件上传源码

前端:




    
    
    Document
    
    


    
    
    


后端:

const express = require('express');
const cors = require('cors');
const path = require('path');
const fs = require('fs');
const multer = require('multer');
const upload = multer({dest:'uploads/'});
const bodyParser = require('body-parser');
const app = express();

app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));

// 存储文件哈希值的对象
const fileHashes = {};

app.post('/upload',upload.single('file'),(req,res) => {
    const file = req.file; // 获取上传的文件对象
    const filename = req.body.filename; // 获取文件名
    const totalChunks = parseInt(req.body.totalChunks); // 获取总块数
    const currentChunk = parseInt(req.body.currentChunk); //获取当前块数
    const chunkPath = path.join(
        "uploads/",
        `${filename}-chunk-${currentChunk}`
    ); //生成当前存储路径

    const chunkStream = fs.createReadStream(file.path); //创建读取文件块的可读流
    const writeStream = fs.createWriteStream(chunkPath); //创建写入当前块的可写流

    chunkStream.pipe(writeStream); //将读取的文件块内容通过管道写入当前块的文件

    chunkStream.on("end", () => {
        fs.unlinkSync(file.path); //读取文件块的流结束后,删除临时文件
        const progress = ((currentChunk + 1) / totalChunks) * 100;
        res.json({ progress }); //相应上传成功的状态
    });
});


router.post("/merge", (req, res) => {
    const filename = req.body.filename; //获取文件名
    const totalChunks = parseInt(req.body.totalChunks);  //获取总块数
    const fileHash = req.body.fileHash //接收到哈希值

    const mergedPath = path.join("uploads", filename); //生成合并后文件的存储路径
    const writeStream = fs.createWriteStream(mergedPath); //创建写入合并后文件的可写流

    const mergeChunks = (index) => {
      if (index === totalChunks) {
        writeStream.end(); //所有块都合并完成后,关闭写入流
        res.sendStatus(200); //响应合并成功的状态
        return;
      }

      const chunkPath = path.join("uploads", `${filename}-chunk-${index}`); //获取当前块的存储路径
      const chunk = fs.readFileSync(chunkPath); //同步读取当前块的内容
      fs.unlinkSync(chunkPath); //删除已合并的块文件

      // 存储文件哈希值,以便进行响应式的检测操作
      fileHashes[fileHash] = true;

      writeStream.write(chunk,() => {
        mergeChunks(index + 1); //递归合并下一块
      });
    };

    mergeChunks(0); //从第一块开始合并
});

// 检查文件是否已存在
app.head('/check-file',(req,res) => {
  const fileHash = req.query.filehash;
  console.log(fileHash,fileHashes);
  if(fileHashes[fileHash]){
    res.sendStatus(200); //文件已存在
  }else{
    res.sendStatus(404); //文件不存在
  }
})



app.listen(3000,() => {
    console.log('Server started on port 3000');
});

你可能感兴趣的:(前端)