web建站教程
  1. 首页
  2. vuejs
  3. js
  4. 好玩
  5. seo教程
  6. 前端知识
  7. 百度echarts
  8. 更多
    php入门
    nodejs
    mockjs
    reactjs
    mysql
    wordpress
    织梦cms
    帝国cms
    git教程
    IT知识
    模板大全
    休息站

html网页上如何把文件压缩成zip代码示列(前端HTML/JavaScript和后端Node.js + Express)

191 ℃
     

如何利用前端HTML/JavaScript和后端Node.js + Express把文本压缩成zip功能,下面web建站小编给大家简单介绍一下具体实现代码!

前端代码示例:

<textarea id="htmlText"></textarea>
<button onclick="compressAndDownload()">压缩并下载为ZIP</button>

<script>
async function compressAndDownload() {
  const htmlText = document.getElementById('htmlText').value;

  if (!htmlText) {
    console.log('请输入或粘贴HTML文本');
    return;
  }

  try {
    const response = await fetch('/api/compress-html-text', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ htmlText })
    });

    if (!response.ok) {
      throw new Error('Failed to compress HTML text');
    }
	
	// 假设服务器返回压缩后ZIP文件的下载URL
    const zipUrl = await response.text(); 
	
	// 打开新的浏览器标签下载生成的ZIP文件
    window.open(zipUrl); 
  } catch (error) {
    console.error('Compression error:', error);
    console.log('压缩过程中发生错误,请稍后重试');
  }
}
</script>

后端代码示例:

const express = require('express');
const archiver = require('archiver');
const fs = require('fs');
const os = require('os');

const app = express();

// 处理HTML文本压缩请求
app.post('/api/compress-html-text', async (req, res) => {
  try {
    const { htmlText } = req.body;

    // 创建临时文件夹存放临时文件
    const tempDir = await fs.promises.mkdtemp(os.tmpdir() + '/html-text-');
    const htmlFilePath = `${tempDir}/input.html`;

    // 将HTML文本写入临时文件
    await fs.promises.writeFile(htmlFilePath, htmlText);

    // 创建ZIP文件并添加HTML文件
    const output = fs.createWriteStream(`${tempDir}/output.zip`);
    const archive = archiver('zip', { zlib: { level: 9 } }); // 最高压缩级别

    archive.pipe(output);
    archive.file(htmlFilePath, { name: 'input.html' });

    await new Promise((resolve, reject) => {
      archive.on('finish', resolve);
      archive.on('error', reject);
      archive.finalize();
    });

    // 返回ZIP文件的下载链接
    res.send(`/download-zip?path=${encodeURIComponent(tempDir)}`);
  } catch (error) {
    console.error('Compression error:', error);
    res.status(500).send('Internal server error');
  }
});

// 提供ZIP文件下载路由
app.get('/download-zip', (req, res) => {
  const tempDir = req.query.path;

  res.download(`${tempDir}/output.zip`, 'compressed_html.zip', err => {
    if (err) {
      console.error('Download error:', err);
    } else {
      // 下载完成后清理临时文件夹
      fs.rm(tempDir, { recursive: true }, err => {
        if (err) {
          console.error('Failed to clean up temporary directory:', err);
        }
      });
    }
  });
});

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

Vue入门需要掌握哪些知识

nodejs如何利用WebSocket实现实时发送数据

nodejs连接mysql失败应该如何解决

nodejs运行报413错误解决方法

前端如何利用nodejs生成二维码

标签: express, html功能, html压缩zip代码, nodejs

上面是“html网页上如何把文件压缩成zip代码示列(前端HTML/JavaScript和后端Node.js + Express)”的全面内容,想了解更多关于 js 内容,请继续关注web建站教程。

当前网址:https://ipkd.cn/webs_16009.html

声明:本站提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请发送到邮箱:admin@ipkd.cn,我们会在看到邮件的第一时间内为您处理!

当前位置: 网站首页 > js
本文共计2016个字,预计阅读时长14分钟
生活小工具,收录了80多款小工具
上一篇: 基于JavaScrip的web动画库——GSAP
下一篇: 免费商用中文字体——优设鲨鱼菲特健康体
x 打工人ai神器