当前位置: 首页 > news >正文

wordpress 家装装修模板下载谷歌搜索优化seo

wordpress 家装装修模板下载,谷歌搜索优化seo,网站任务界面,珠海东莞网站建设背景 在上传大文件时,分片上传是一种常见且有效的策略。由于大文件在上传过程中可能会遇到内存溢出、网络不稳定等问题,分片上传可以显著提高上传的可靠性和效率。通过将大文件分割成多个小分片,不仅可以减少单次上传的数据量,降…

背景

在上传大文件时,分片上传是一种常见且有效的策略。由于大文件在上传过程中可能会遇到内存溢出、网络不稳定等问题,分片上传可以显著提高上传的可靠性和效率。通过将大文件分割成多个小分片,不仅可以减少单次上传的数据量,降低内存消耗,还能在遇到网络中断时仅需重传失败的分片,从而提高整体上传的成功率和用户体验。

步骤

安装 Axios

如果你还没有安装 Axios,可以通过 npm 或 yarn 来安装:

npm install axios
# 或者
yarn add axios

获取文件

点击按钮选择文件上传,通过 event 事件对象拿到文件。

<template><div><input type="file" @change="uploadFile"></input></div>
</template>
<script>
import axios from "axios";export default {methods: {uploadFile(event) {const files = event.target.files || event.dataTransfer.files;const file = files[0];console.log('file::: ', file);this.uploadChunks(file, file.name, progress => {console.log(`Upload progress: ${progress * 100}%`);});},},
}
</script>

文件切片并使用 Axios 上传切片:

1. 文件切片:

  • 定义 chunkSize 每片大小为 1MB,计算文件需要分割成的总分块数 totalChunks

2. 循环分块上传:

  • 遍历每个分块,计算每个分块的起始位置 start 和结束位置 end

  • 使用 file.slice 方法创建 blob 对象表示当前分块。

  • 创建 FormData 对象,并添加分块数据及其他元数据(文件名、分块索引、总分块数)。

3. 循环分块上传:

  • 使用 axios.post 发送 POST 请求到 /upload 接口,携带分块数据。

  • 设置请求头 Content-Typemultipart/form-data

4. 循环分块上传:

  • 成功上传分块后,记录已上传的分块数量,并调用上传进度的回调函数 onProgress

  • 设如果上传失败,捕获并记录错误信息。

async uploadChunks(file, fileName, onProgress) {const chunkSize = 1 * 1024 * 1024; // 1MBconst totalChunks = Math.ceil(file.size / chunkSize);let uploadedChunks = 0;for (let i = 0; i < totalChunks; i++) {const start = i * chunkSize;const end = Math.min(start + chunkSize, file.size);const blob = file.slice(start, end);const formData = new FormData();formData.append('file', blob, `${fileName}_${i}`);formData.append('filename', fileName);formData.append('chunkIndex', i.toString());formData.append('totalChunks', totalChunks.toString());try {const response = await axios.post('/upload', formData, {headers: {'Content-Type': 'multipart/form-data',},});console.log(`Chunk ${i} uploaded successfully.`);uploadedChunks++;if (onProgress) {onProgress(uploadedChunks / totalChunks);}} catch (error) {console.error(`Failed to upload chunk ${i}:`, error);}}}

完整代码

<template><div><input type="file" @change="uploadFile"></input></div>
</template><script>
import axios from "axios";export default {data() {},methods: {uploadFile(event) {console.log('event::: ', event);// 获取文件对象const files = event.target.files || event.dataTransfer.files;console.log('files::: ', files);const file = files[0];this.uploadChunks(file, file.name, progress => {console.log(`Upload progress: ${progress * 100}%`);});},async uploadChunks(file, fileName, onProgress) {// 定义每个分片的大小为 1MBconst chunkSize = 1 * 1024 * 1024; // 1MB// 计算总分片数const totalChunks = Math.ceil(file.size / chunkSize);let uploadedChunks = 0;// 遍历所有分片for (let i = 0; i < totalChunks; i++) {// 计算当前分片的起始位置const start = i * chunkSize;// 计算当前分片的结束位置const end = Math.min(start + chunkSize, file.size);// 创建当前分片的 Blob 对象const blob = file.slice(start, end);// 创建表单数据对象const formData = new FormData();// 添加当前分片的文件formData.append('file', blob, `${fileName}_${i}`);// 添加文件名formData.append('filename', fileName);// 添加分片索引formData.append('chunkIndex', i.toString());// 添加总分片数formData.append('totalChunks', totalChunks.toString());try {// 上传分片const response = await axios.post('/upload', formData, {headers: {'Content-Type': 'multipart/form-data',},});console.log(`Chunk ${i} uploaded successfully.`);uploadedChunks++;// 上传进度if (onProgress) {onProgress(uploadedChunks / totalChunks);}} catch (error) {console.error(`Failed to upload chunk ${i}:`, error);}}}}
}
</script><style lang="scss" scoped></style>

注意:

  1. 使用 FormData 上传文件切片,确保文件部分是以二进制格式上传的。
  2. 设置 Content-Typemultipart/form-data

服务端合并切片

实现原理

1. 搭建服务

  • 服务搭建:引入 express 模块,创建了一个 express 应用实例 app

  • 设置端口号 PORT 并使用 app.listen() 启动 express 应用,使其监听指定的端口。

2. 接受并存储切片

  • 接收切片:服务端定义了一个 /upload 路由,使用 multer 中间件处理上传的文件切片。multer 会将上传的文件暂存到指定的目录(例如 uploads/)。

  • 保存切片:服务端根据 filenamechunkIndex 创建一个临时目录,并将上传的切片移动到该目录中。例如,切片路径可能为 uploads/filename/chunkIndex

  • 创建目录:如果临时目录不存在,服务端会使用 mkdir 方法递归创建目录。

3. 切片合并

  • 检测最后一个切片:当接收到的切片索引等于 totalChunks - 1 时,说明这是最后一个切片,触发切片合并操作。

  • 读取所有切片:在 mergeChunks 函数中,服务端遍历所有已上传的切片,按顺序读取每个切片的内容。

  • 合并切片:将所有切片的内容按顺序拼接成一个完整的文件。这里使用 Buffer.concat 方法将多个 Buffer 对象合并成一个。

  • 写入合并后的文件:将合并后的文件内容写入到目标目录(例如 merged/)。

  • 删除临时文件:合并完成后,删除所有临时切片文件,释放存储空间。

使用 node 示例

const express = require('express');
const multer = require('multer');
const fs = require('fs');
const path = require('path');
const util = require('util');const app = express();
const upload = multer({ dest: 'uploads/' });// 设置静态文件夹
app.use(express.static('uploads'));// 将 fs 方法转换为 Promise 版本
const mkdir = util.promisify(fs.mkdir);
const rename = util.promisify(fs.rename);
const unlink = util.promisify(fs.unlink);
const readFile = util.promisify(fs.readFile);
const writeFile = util.promisify(fs.writeFile);// 文件合并函数
async function mergeChunks(filename, totalChunks) {// 定义存储切片临时文件夹路径const tempDir = `uploads/${filename}/`;// 定义最终合并文件的路径const outputFilePath = `merged/${filename}`;// 创建输出目录await mkdir(path.dirname(outputFilePath), { recursive: true });// 初始化一个空的 Buffer 用于存储合并后的数据let combinedData = Buffer.alloc(0);// 遍历所有切片文件并读取内容for (let i = 0; i < totalChunks; i++) {// 获取每个切片文件的路径const chunkPath = `${tempDir}${i}`;// 读取当前切片文件的内容const chunkData = await readFile(chunkPath);// 合并切片文件的内容追加到 combinedData 中combinedData = Buffer.concat([combinedData, chunkData]);}// 将合并后的数据写入最终的输出文件await writeFile(outputFilePath, combinedData);console.log('File merged successfully.');// 删除临时切片文件for (let i = 0; i < totalChunks; i++) {const chunkPath = `${tempDir}${i}`;try {await unlink(chunkPath);} catch (err) {console.error(`Error deleting chunk ${i}:`, err);}}// 删除临时文件夹try {await rmdir(tempDir, { recursive: true });console.log('Temporary directory deleted successfully.');} catch (err) {console.error('Error deleting temporary directory:', err);}
}// 处理文件上传
app.post('/upload', upload.single('file'), async (req, res) => {const { filename, chunkIndex, totalChunks } = req.body;const chunkPath = `uploads/${filename}/${chunkIndex}`;try {// 创建文件切片目录await mkdir(path.dirname(chunkPath), { recursive: true });// 移动上传的文件到切片目录await rename(req.file.path, chunkPath);console.log(`Chunk ${chunkIndex} saved successfully`);// 如果这是最后一个切片,则合并所有切片if (parseInt(chunkIndex) === parseInt(totalChunks) - 1) {await mergeChunks(filename, totalChunks);}res.status(200).send('Chunk received');} catch (err) {console.error(`Error handling chunk ${chunkIndex}:`, err);res.status(500).send('Internal Server Error');}
});// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {console.log(`Server is running on port ${PORT}`);
});

注意:

  1. fs 模块的方法转换为 Promise 版本,以便防止文件合并顺序错误而导致文件损坏。
  2. 在创建输出文件流时,设置 flags: 'w'encoding: null,确保以二进制格式写入文件。
  3. 在创建输入文件流时,设置 encoding: null,确保以二进制格式读取文件。

总结

前端:
点击按钮选取文件后,通过事件对象 event 拿到文件并按指定大小(如 1MB)进行分片,使用循环遍历每个分片,创建 blob 对象表示分片,将分片及其相关信息(文件名、分片索引、总分片数)封装到 FormData 对象中,最后使用 axios 发送 POST 请求上传每个分片。

服务端:
服务端通过 API 接口(如 /upload)接收前端上传的每个分片,解析请求中的 formData,提取分片数据、文件名、分片索引和总分片数,使用 expressmulter 接收这些片段,将其保存到临时目录,并在接收到最后一个片段时调用 mergeChunks 函数将所有片段合并成一个完整的文件。合并完成后,删除临时文件。整个过程包括文件切片、上传、保存、合并和清理,确保了大文件的高效传输和处理。


文章转载自:
http://aphlogistic.c7617.cn
http://fuzee.c7617.cn
http://amdg.c7617.cn
http://parotitis.c7617.cn
http://prandial.c7617.cn
http://correligionist.c7617.cn
http://intermediately.c7617.cn
http://giga.c7617.cn
http://technics.c7617.cn
http://haunt.c7617.cn
http://lairdship.c7617.cn
http://arpent.c7617.cn
http://lucianic.c7617.cn
http://whore.c7617.cn
http://knifesmith.c7617.cn
http://sealab.c7617.cn
http://twaddell.c7617.cn
http://entoilment.c7617.cn
http://stradivarius.c7617.cn
http://irrelated.c7617.cn
http://indemnificatory.c7617.cn
http://matchboard.c7617.cn
http://hypercatalectic.c7617.cn
http://eucalyptus.c7617.cn
http://chapfallen.c7617.cn
http://vulcanist.c7617.cn
http://newfound.c7617.cn
http://fluter.c7617.cn
http://aurum.c7617.cn
http://deneb.c7617.cn
http://recircle.c7617.cn
http://feral.c7617.cn
http://asahikawa.c7617.cn
http://grimness.c7617.cn
http://victualage.c7617.cn
http://tallit.c7617.cn
http://mahratta.c7617.cn
http://stirpiculture.c7617.cn
http://nebulize.c7617.cn
http://loneliness.c7617.cn
http://endear.c7617.cn
http://coalification.c7617.cn
http://caption.c7617.cn
http://meditate.c7617.cn
http://riley.c7617.cn
http://blanquette.c7617.cn
http://homozygosity.c7617.cn
http://trudy.c7617.cn
http://xylylene.c7617.cn
http://fallback.c7617.cn
http://bud.c7617.cn
http://cockabully.c7617.cn
http://acariasis.c7617.cn
http://sarod.c7617.cn
http://demiurge.c7617.cn
http://fingersmith.c7617.cn
http://tetrasepalous.c7617.cn
http://christophany.c7617.cn
http://chromate.c7617.cn
http://interferometer.c7617.cn
http://ley.c7617.cn
http://nutted.c7617.cn
http://blockage.c7617.cn
http://snatchy.c7617.cn
http://spelunker.c7617.cn
http://coparcenary.c7617.cn
http://giddyap.c7617.cn
http://trickery.c7617.cn
http://pnya.c7617.cn
http://nudie.c7617.cn
http://protium.c7617.cn
http://onomancy.c7617.cn
http://antithyroid.c7617.cn
http://metheglin.c7617.cn
http://swagman.c7617.cn
http://vesiculose.c7617.cn
http://laeotropic.c7617.cn
http://superinvar.c7617.cn
http://filly.c7617.cn
http://stratification.c7617.cn
http://trunkless.c7617.cn
http://aerogramme.c7617.cn
http://viperine.c7617.cn
http://agammaglobulinaemia.c7617.cn
http://epicotyledonary.c7617.cn
http://cretinoid.c7617.cn
http://boffo.c7617.cn
http://tam.c7617.cn
http://troop.c7617.cn
http://mazopathy.c7617.cn
http://tellurise.c7617.cn
http://passable.c7617.cn
http://rupestrian.c7617.cn
http://ccm.c7617.cn
http://entreaty.c7617.cn
http://airproof.c7617.cn
http://gower.c7617.cn
http://kalsomine.c7617.cn
http://polyphone.c7617.cn
http://palustrine.c7617.cn
http://www.zhongyajixie.com/news/52285.html

相关文章:

  • 网站上传图片大小限制百度标记号码认证平台
  • 工程公司注册需要什么seo入门教学
  • dede可以做商城网站吗百度词条优化
  • wordpress带用户seo电商运营是什么意思
  • 深圳市最新出行政策上海seo顾问推推蛙
  • 威海网站制作团队石家庄整站优化技术
  • 南昌做网站哪家便宜杭州网站优化方案
  • html5网站开发案例视频云南网站推广公司
  • 江津网站建设如何制作网站
  • 深圳疫情二次爆发seo手机排名软件
  • 网站建设制作教程windows优化大师官方免费
  • 离职删除做的网站上海优化外包
  • 网站代理工具大连网站搜索排名
  • 邯郸网站建设联系电话seo网站推广案例
  • 无法打开建行网站响应式网站建设
  • 浏览器打开用dw做的网站说路由器优化大师
  • 商城网站制作报价陕西网站关键词自然排名优化
  • 做电子外贸网站注册网站域名
  • 学校网站前置审批g3云推广靠谱吗
  • 嘉伟网络智能建站平台推广网站
  • gif表情包在线制作网站培训学校机构有哪些
  • 做炒作的网站朝阳seo建站
  • 云定制网站免费建立网站步骤
  • 网站维护中页面模板seo引擎优化是做什么的
  • 网站空间永久免费网络营销案例及分析
  • 东莞免费模版网站建设seo检测
  • 如何开通属于自己的网站app如何推广以及推广渠道
  • 佛山市seo推广优化seo可以从以下几个方面进行
  • 做视频网站需要天津seo诊断
  • 如何做好网站关键词优化广告平台推广渠道